EN
React - functional component force re-render
3 points
In this article, we would like to show you how to force re-render in a functional component in React.
Quick solution:
xxxxxxxxxx
1
// paste hook definition to project:
2
const useForceRerendering = () => {
3
const [counter, setCounter] = React.useState(0);
4
return () => setCounter(counter => counter + 1);
5
};
6
7
// add hook at beginning of a component:
8
const forceRerendering = useForceRerendering();
9
10
// for re-rendering always when it is necessary with:
11
forceRerendering();
In below example we use the fact: any change of state causes component rendering, so using e.g. counter
state we are able to force re-rendering always on setCounter()
call.
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 [counter, setCounter] = React.useState(0);
7
console.log('App component rednering...');
8
return (
9
<button onClick={() => setCounter(counter => counter + 1)}>force re-rendering</button>
10
);
11
};
12
13
const root = document.querySelector('#root');
14
ReactDOM.render(<App />, root);
In this section, we want to show how to create our own hook that let us force component rerendering by simple method call.
Note: in below example when we call
forceRerendering()
component is rerendered.
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 useForceRerendering = () => {
6
const [counter, setCounter] = React.useState(0);
7
return () => setCounter(counter => counter + 1);
8
};
9
10
const App = () => {
11
const forceRerendering = useForceRerendering();
12
console.log('App component rednering...');
13
return (
14
<button onClick={() => forceRerendering()}>force re-rendering</button>
15
);
16
};
17
18
const root = document.querySelector('#root');
19
ReactDOM.render(<App />, root);