Snippet

useForceUpdate()

edit

In React, a component will update whenever state is updated. So all we need to make an update happen is call a setState with a new value. Simplest way to do this is flip a boolean.

const useForceUpdate = () => {
  const [, setState] = React.useState(true)
  const forceUpdate = React.useCallback(() => {
    setState(s => !s)
  }, [])

  return forceUpdate
}

This can be useful when using useRef. Changes to refs won’t trigger a component to update. Calling forceUpdate after setting a ref may be the trick you’re looking for.


Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.

Kyle Shevlin's face, which is mostly a beard with eyes

Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.

Agathist
Good software by good people.
Visit https://agath.ist to learn more
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.
Logo for Array.reduce()
Array.reduce()
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.