How to Force Rerender Using React Hooks

Irakli Tchigladze Feb 02, 2024
  1. Use the .forceUpdate() Method in React
  2. Force Rerender With Hooks in React
How to Force Rerender Using React Hooks

The majority of JavaScript developers choose to build applications in React. Its popularity can be attributed to its features, mainly the Virtual DOM.

React components have a shouldComponentUpdate() method that internally tracks changes to state and props and updates the view accordingly.

Usually, this default behavior is more than sufficient to build and run complex React applications. However, developers need to bypass the default behavior in rare cases and rerender the component manually.

Use the .forceUpdate() Method in React

The shouldComponentUpdate() is the default method that updates the view of React components. It is triggered automatically whenever the component’s state or props change.

If the component receives data that doesn’t come from state or props, React developers can use the component.forceUpdate() method to force a rerender and update the view.

Once triggered, this method will update each child of the component. It’s not recommended to use the component.forceUpdate() method unless you’re sure you need it.

It may be necessary for testing or other edge cases.

Force Rerender With Hooks in React

React Version 16.8 introduced hooks, which added many features to functional components that they didn’t have before.

For instance, now functional components can maintain state and handle side effects using the useEffect() hook.

You can use useState and useReducer hooks to force a React component to rerender.

In our example, we are going to use the useReducer hook:

export default function App() {
  const [, forceRerender] = useReducer(x => x + 1, 0)
  return (
    <div className="App">
      <button onClick={() => forceRerender()}>Force Update</button>
    </div>
  );
}

As we can see, we don’t even set the variable to store the state. Because we only use the useReducer() hook to force an update.

Here, we have a simple button with an onClick attribute, which executes the forceRerender function every time the button is clicked.

You can try out the code on codesandbox.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn

Related Article - React Hooks