EN
React - force update/rendering without setState
4
points
In this article, we would like to show you how to force component to re-render in React.
Quick solution:
import { useReducer } from 'react'
const [, forceUpdate] = useReducer(x => x + 1, 0);
// some code...
forceUpdate()
By default, the component re-renders when it detects a state change, but sometimes we want to force a re-rendering. For class components, there was a forceUpdate()
method, but not for functional components.
However, this can be remedied by increasing the counter with the useReducer
hook.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [ignored, forceUpdate] = React.useReducer(x => x + 1, 0);
return (
<div>
<button onClick={forceUpdate}>Force update</button>
<p>Forced update counter: {ignored}</p>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Note:
When we use
setState
with the same state value as the previous one, it will be detected by React and the component will not re-render.
See also:
- React - functional component force re-render (example with useState).