A good[ish] website
Web development blog, loads of UI and JavaScript topics
Here’s how to force a re-render on a function-style React component. Spoiler alert: it’s really simple.
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:
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.
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.
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)
}
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.
Comments would go here, but the commenting system isn’t ready yet, sorry.