clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Force re-render function React component (or class component)

Filed under: JavaScript— Tagged with: React

Here’s how to force a re-render on a function-style React component. Spoiler alert: it’s really 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.

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!