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:
// paste hook definition to project:
const useForceRerendering = () => {
const [counter, setCounter] = React.useState(0);
return () => setCounter(counter => counter + 1);
};
// add hook at beginning of a component:
const forceRerendering = useForceRerendering();
// for re-rendering always when it is necessary with:
forceRerendering();
Force rerendering with state example
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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [counter, setCounter] = React.useState(0);
console.log('App component rednering...');
return (
<button onClick={() => setCounter(counter => counter + 1)}>force re-rendering</button>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Force rerendering hook example
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.
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const useForceRerendering = () => {
const [counter, setCounter] = React.useState(0);
return () => setCounter(counter => counter + 1);
};
const App = () => {
const forceRerendering = useForceRerendering();
console.log('App component rednering...');
return (
<button onClick={() => forceRerendering()}>force re-rendering</button>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);