Here’s how to force a re-render on a function-style React component. Spoiler alert: it’s very simple.
Why would you want to force a re-render?
For example, when you need to fetch fresh data and re-render a graph for example. Below is some imaginary random data, you can click the refresh button to regenerate it:
How to re-render?
It’s really simple: when you update the component’s state, it will re-render.
React also has a helper method for that:
this.forceUpdate()Unfortunately that only works on Class components.
Force a re-render in a function component
For function components, we can make a state specifically for this, lets call it
refresh. The value is 0, and then we increment it when we want a refresh:
const Graph = () => {
const [refresh, setRefresh] = React.useState(0)
return (
<Box>
<Wrap>
{getData().map(amount => (
<Item height={amount} key={amount} />
))}
</Wrap>
<button onClick={() => setRefresh(refresh + 1)}>Refresh data</button>
</Box>
)
}Make sure you call data from inside the component, I’m running the getData
function, which gives me a fresh set of
random numbers.
A refresh React hook
If you use it a lot, you could make a re-render hook:
const useRefresh = () => {
const [refresh, setRefresh] = React.useState(0)
return () => setRefresh(refresh + 1)
}Conclusions
So, the only way to re-render is to update the state 💁♂️ I guess the
forceUpdate() helper does the state update under the hood.
That’s about it. Hope this was helpful.