Categories
React Answers

How to force a React component to rerender without calling setState?

Spread the love

To force a React component to rerender without calling setState, we can keep a state with useReducer.

For instance, we write

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

const handleClick = () => {
  forceUpdate();
};

to call the useReducer hook to return an array withe forceUpdate function.

We call useReducer with a function toi return a new state each time forceUpdate is called.

Then we call forceUpdate to update the state returned by useReducer to trigger re-rendering.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *