Sometimes you need to force react to update a functional component.
But, how to do this?
Class components:
We just need to update the current state:
this.setState({ state: this.state });
React has a function to do this without explicitly set state to the same state:
this.forceUpdate()
Functional components:
The forceUpdate method is not available when you are using functional components, so, how to do this?
This could be as simple as:
const [remountCount, setRemountCount] = useState(0); const refresh = () => setRemountCount(remountCount + 1);
You just need to call refresh method to re-render the react component.
How to turn this into a readable react hook?
Solution from: https://stackoverflow.com/questions/46240647/react-how-can-i-force-render-a-function-component
Create a new hook called useForceUpdate:
import React, { useState } from 'react'; //create your forceUpdate hook function useForceUpdate(){ const [value, setValue] = useState(0); // integer state return () => setValue(value => ++value); // update the state to force render }
And then call it from your component:
import React, { useState } from 'react'; import { useForceUpdate } from '../hooks'; function MyComponent() { // use your hook here const forceUpdate = useForceUpdate(); return ( <div> {/*Clicking on the button will force to re-render like force update does */} <button onClick={forceUpdate}> Click to re-render </button> </div> ); }
Thank you guys!
I’ll try to write more articles.