1

How do I get forceUpdate() working to rerender component? I receive the following error, Cannot read property 'forceUpdate' of undefined

function App() {

  const renderData = () => {
    console.log('render');
    this.forceUpdate();
  }

  return (
    <div>
      Test
      <button onClick={renderData}> render data </button>
    </div>
  );
}

Error:

TypeError: Cannot read property 'forceUpdate' of undefined

const renderData = () => {
console.log('render');
this.forceUpdate();

Resource: Can you force a React component to rerender without calling setState?

mattsmith5
  • 540
  • 4
  • 29
  • 67

1 Answers1

1

this.forceUpdate() is only available in class based components

You can force an update by updating the state:

const [someVar, setSomeVar] = useState(null);

const renderData = () => {
    console.log('render');
    setSomeVar(true);
}

Or taking inspiration from here, create your own forceUpdate function:

function useForceUpdate(){
    const [value, setValue] = useState(0); // integer state
    return () => setValue(value => value + 1); // update the state to force render
}

I would strongly suggest not to do this, this is a sign that you should probably structure your logic differently.

gunwin
  • 4,578
  • 5
  • 37
  • 59