266

I have a function component, and I want to force it to re-render.

How can I do so?
Since there's no instance this, I cannot call this.forceUpdate().

4
  • 1
    no, a stateless component does not have a state. Use a class instead Commented Sep 15, 2017 at 13:24
  • 4
    Do you really mean "stateless component" and not "functional component"?
    – Chris
    Commented Sep 15, 2017 at 13:28
  • 3
    In order to update a stateless component, the props passed in need to change. Commented Sep 15, 2017 at 20:17
  • 2
    beside props you can use hook useState, and components will be re-render when it changes Commented Feb 16, 2020 at 4:17

13 Answers 13

443

🎉 You can now, using React hooks

👉🏻 using useReducer (short answer)

const [, forceUpdate] = useReducer(x => x + 1, 0);

From React FAQ

How to use:

function MyComponent(){
  const [, forceUpdate] = useReducer(x => x + 1, 0);

  return (
    <div onClick={forceUpdate}>
      Click me to refresh
    </div>
  );
}

👉🏻 Using useState (more explicit answer)

Using react hooks, you can now call useState() in your function component.

useState() will return an array of 2 things:

  1. A value, representing the current state.
  2. Its setter. Use it to update the value.

Updating the value by its setter will force your function component to re-render,
just like forceUpdate does:

import React, { useState } from 'react';

//create your forceUpdate hook
function useForceUpdate(){
    const [value, setValue] = useState(0); // integer state
    return () => setValue(value => value + 1); // update state to force render
    // A function that increment 👆🏻 the previous state like here 
    // is better than directly setting `setValue(value + 1)`
}

function MyComponent() {
    // call your hook here
    const forceUpdate = useForceUpdate();
    
    return (
        <div>
            {/*Clicking on the button will force to re-render like force update does */}
            <button onClick={forceUpdate}>
                Click to re-render
            </button>
        </div>
    );
}

You can find a demo here.

The component above uses a custom hook function (useForceUpdate) which uses the react state hook useState. It increments the component's state's value and thus tells React to re-render the component.


EDIT

In an old version of this answer, the snippet used a boolean value, and toggled it in forceUpdate(). Now that I've edited my answer, the snippet use a number rather than a boolean.

Why ? (you would ask me)

Because once it happened to me that my forceUpdate() was called twice subsequently from 2 different events, and thus it was reseting the boolean value at its original state, and the component never rendered.

This is because in the useState's setter (setValue here), React compare the previous state with the new one, and render only if the state is different.

27
  • 16
    Nothing on that page has any information about using Hooks to call forceUpdate.
    – jdelman
    Commented Dec 21, 2018 at 14:47
  • 1
    For now, you're right it's better, because, even tough hooks are not released yet, you can still use it in beta. But once they are released, there is no reason class component will be better. Using hooks makes code cleaner than class component, as the video below in the reactconf shows. Anyway, the question is if this is possible. The answer now changes from "No" to "Yes" because of hooks. youtube.com/watch?v=wXLf18DsV-I
    – Yairopro
    Commented Dec 22, 2018 at 19:54
  • 2
    Hi @DanteTheSmith. By "Top level", it means that hooks must not be called from inside a condition or loop, as you said. But I can tell you that you can call them from inside another function. And that means creating a custom hook. Dan Abramov, as he presents React hooks in the React conf, clearly demonstrate that this is the cleanest and best way to share logic between functional components: youtu.be/dpw9EHDh2bM?t=2753
    – Yairopro
    Commented May 10, 2019 at 12:53
  • 5
    @meandre Yes it definitely compares. We are talking about the useState hook, not the class' setState which indeed doesn't make a comparaison (unless you implement shouldUpdate method). See the same demo I posted, but with a static value used for setState, it doesn't render again: codesandbox.io/s/determined-rubin-8598l
    – Yairopro
    Commented Oct 15, 2019 at 13:18
  • 5
    an empty object will do the same trick
    – Snowmanzzz
    Commented Nov 18, 2021 at 10:58
92

Official FAQ now recommends this way if you really need to do it:

  const [ignored, forceUpdate] = useReducer(x => x + 1, 0);

  function handleClick() {
    forceUpdate();
  }
2
  • 57
    and you can make your code 7 bytes shorter and don't create unused variable: const [, forceUpdate] = useReducer(x => x + 1, 0); Commented May 7, 2020 at 10:17
  • 16
    Shorter 👉 const forceUpdate = useReducer(x => x + 1, 0)[1]
    – vsync
    Commented Aug 29, 2022 at 7:04
78

Update react v16.8 (16 Feb 2019 realease)

Since react 16.8 released with hooks, function components have the ability to hold persistent state. With that ability you can now mimic a forceUpdate:

function App() {
  const [, forceUpdate] = React.useReducer(o => !o);
  console.log("render");
  return (
    <div>
      <button onClick={forceUpdate}>Force Render</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"/>

Note that this approach should be re-considered and in most cases when you need to force an update you probably doing something wrong.


Before react 16.8.0

No you can't, State-Less function components are just normal functions that returns jsx, you don't have any access to the React life cycle methods as you are not extending from the React.Component.

Think of function-component as the render method part of the class components.

2
  • 13
    that's not forcing a re-render, that's just a normal render. when you want to force rendering, it's usually a case when you want to run the render method when it wasn't designed to run, for example when there are no new props or state changes. you can't force the render function as there is no renderfunction on stateless components. stateless components doesn't extends React.Component they are just plain functions that returns jsx.
    – Sagiv b.g
    Commented Oct 31, 2017 at 12:04
  • 3
    Props for "when you need to force an update you're probably doing something wrong" - I knew that was the case, but this just prompted me to take one more good look at my useEffect hook. Commented Jul 30, 2019 at 21:31
18

Simplest way 👌

if you want to force a re-render, add a dummy state you can change to initiate a re-render.

const rerender = useState();

...
setRerender(Symbol());     //built in Symbol() always returns unique value

And this will ensure a re-render, And you can call setRerender(Symbol()) anywhere, whenever you want :)

4
  • 4
    See another answer comment thread for the situation where this does not work (called twice scenario) Commented Jun 9, 2022 at 2:19
  • This doesn't work sometimes as @GreenAsJade mentioned. Commented Jan 3 at 10:53
  • This never works.
    – jtiscione
    Commented Mar 5 at 18:39
  • Edit made to make it always work
    – Abraham
    Commented Mar 6 at 19:35
11

I used a third party library called use-force-update to force render my react functional components. Worked like charm. Just use import the package in your project and use like this.

import useForceUpdate from 'use-force-update';

const MyButton = () => {

  const forceUpdate = useForceUpdate();

  const handleClick = () => {
    alert('I will re-render now.');
    forceUpdate();
  };

  return <button onClick={handleClick} />;
};
1
  • 9
    To save you a click - useForceUpdate uses useCallback as mentioned in other answers. This lib is just a utility lib to save you few keystrokes.
    – asyncwait
    Commented Feb 8, 2020 at 4:45
5

Best approach - no excess variables re-created on each render:

const forceUpdateReducer = (i) => i + 1

export const useForceUpdate = () => {
  const [, forceUpdate] = useReducer(forceUpdateReducer, 0)
  return forceUpdate
}

Usage:

const forceUpdate = useForceUpdate()

forceUpdate()
2

If you already have a state inside the function component and you don't want to alter it and requires a re-render you could fake a state update which will, in turn, re-render the component

const [items,setItems] = useState({
   name:'Your Name',
   status: 'Idle'
})
const reRender = () =>{
setItems((state) => [...state])
}

this will keep the state as it was and will make react into thinking the state has been updated

1

This can be done without explicitly using hooks provided you add a prop to your component and a state to the stateless component's parent component:

const ParentComponent = props => {
  const [updateNow, setUpdateNow] = useState(true)

  const updateFunc = () => {
    setUpdateNow(!updateNow)
  }

  const MyComponent = props => {
    return (<div> .... </div>)
  }

  const MyButtonComponent = props => {
    return (<div> <input type="button" onClick={props.updateFunc} />.... </div>)
  }

  return (
    <div> 
      <MyComponent updateMe={updateNow} />
      <MyButtonComponent updateFunc={updateFunc}/>
    </div>
  )
}
1

The accepted answer is good. Just to make it easier to understand.

Example component:

export default function MyComponent(props) {

    const [updateView, setUpdateView] = useState(0);

    return (
        <>
            <span style={{ display: "none" }}>{updateView}</span>
        </>
    );
}

To force re-rendering call the code below:

setUpdateView((updateView) => ++updateView);
1

None of these gave me a satisfactory answer so in the end I got what I wanted with the key prop, useRef and some random id generator like shortid.

Basically, I wanted some chat application to play itself out the first time someone opens the app. So, I needed full control over when and what the answers are updated with the ease of async await.

Example code:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// ... your JSX functional component, import shortid somewhere

const [render, rerender] = useState(shortid.generate())

const messageList = useRef([
    new Message({id: 1, message: "Hi, let's get started!"})
])

useEffect(()=>{
    async function _ () {
      await sleep(500)
      messageList.current.push(new Message({id: 1, message: "What's your name?"}))
      // ... more stuff
      // now trigger the update
      rerender(shortid.generate())
   } 
   _()
}, [])

// only the component with the right render key will update itself, the others will stay as is and won't rerender.
return <div key={render}>{messageList.current}</div> 

In fact this also allowed me to roll something like a chat message with a rolling .

const waitChat = async (ms) => {
    let text = "."
    for (let i = 0; i < ms; i += 200) {
        if (messageList.current[messageList.current.length - 1].id === 100) {
            messageList.current = messageList.current.filter(({id}) => id !== 100)
        }
        messageList.current.push(new Message({
            id: 100,
            message: text
        }))
        if (text.length === 3) {
            text = "."
        } else {
            text += "."
        }
        rerender(shortid.generate())
        await sleep(200)
    }
    if (messageList.current[messageList.current.length - 1].id === 100) {
        messageList.current = messageList.current.filter(({id}) => id !== 100)
    }
}
2
  • It is never a good idea to use await in a React's built in hooks like useEffect. Also this code won't work because 'await' is not in an 'async' function in the first snippet. If you have some arbitrary loader or plugin that enables this, you should mention that because its not the default configuration. Commented Mar 17, 2021 at 22:54
  • 1
    updated it to include a trivial example of how to use async/await in useEffect. Unfortunately there are often very good usecases for using async/await in useEffect, no matter what your personal preferences are. Commented Mar 18, 2021 at 8:13
1

If you are using functional components with version < 16.8. One workaround would be to directly call the same function like

import React from 'react';

function MyComponent() {
    const forceUpdate = MyComponent();
    
    return (
        <div>
            <button onClick={forceUpdate}>
                Click to re-render
            </button>
        </div>
    );
}

But this will break if you were passing some prop to it. In my case i just passed the same props which I received to rerender function.

1

For me just updating the state didn't work. I am using a library with components and it looks like I can't force the component to update.

My approach is extending the ones above with conditional rendering. In my case, I want to resize my component when a value is changed.

//hook to force updating the component on specific change
const useUpdateOnChange = (change: unknown): boolean => {
  const [update, setUpdate] = useState(false);

  useEffect(() => {
    setUpdate(!update);
  }, [change]);

  useEffect(() => {
    if (!update) setUpdate(true);
  }, [update]);

  return update;
};

const MyComponent = () => {
  const [myState, setMyState] = useState();
  const update = useUpdateOnChange(myState);

  ...

  return (
    <div>
      ... ...
      {update && <LibraryComponent />}
    </div>
  );
};

You need to pass the value you want to track for change. The hook returns boolean which should be used for conditional rendering.

When the change value triggers the useEffect update goes to false which hides the component. After that the second useEffect is triggered and update goes true which makes the component visible again and this results in updating (resizing in my case).

1
  • A national tragedy after one hour of searching this is the first answer that worked for me, insane and amazing, all at the same time! Thank you!
    – petrosmm
    Commented Apr 25 at 1:49
-3

BEST WAY TO KEEP CONSOLE LOG AND CHECK WHETHER THE USE EFFECT HOOK is TRIGGERING OR NOT ON EACH TIME WHEN WE SET

const [multiSelectList, setMultiSelectList] = useState<string[]>();
    
    setMultiSelectList(multiDropDownValues);
    
      useEffect(()=>{
          console.log("triggers from combo multi on multiSelectList changes"+JSON.stringify(multiSelectList));
        },[multiSelectList]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.