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:
xxxxxxxxxx
1
import { useReducer } from 'react'
2
3
const [, forceUpdate] = useReducer(x => x + 1, 0);
4
// some code...
5
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:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [ignored, forceUpdate] = React.useReducer(x => x + 1, 0);
7
return (
8
<div>
9
<button onClick={forceUpdate}>Force update</button>
10
<p>Forced update counter: {ignored}</p>
11
</div>
12
);
13
};
14
15
const root = document.querySelector('#root');
16
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.
- React - functional component force re-render (example with useState).