How to Force Rerender With Hooks in React

How to Force Rerender With Hooks in React

Ferenc Almasi β€’ πŸ”„ 2021 July 13 β€’ πŸ“– 2 min read

You can force re-renders of your components in React with a custom hook that uses the built-in useState hook:

The following hook should only be used in exceptional cases. Only re-render your component when state changes.

import React, { useState } from 'react'

// Create a custom useForceUpdate hook with useState
const useForceUpdate = () => useState()[1];

// Call it inside your component
const Hooks = () => {
  const forceUpdate = useForceUpdate();

  return (
    <button onClick={forceUpdate}>
      Update me
Copied to clipboard!

The example above is equivalent to the functionality of the forceUpdate method in class-based components. This hook works in the following way:

  • The useState hook β€” and any other hook for that matter β€” returns an array with two elements, a value (with the initial value being the one you pass to the hook function) and an updater function.
  • In the above example, we are instantly calling the updater function, which in this case is called with undefined, so it is the same as calling updater(undefined).

If you would like to see it in action, give it a try on Codesandbox

Try the hook on codesandbox
How to Force Rerender With Hooks in React
If you would like to see more Webtips, follow @flowforfrank

If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.

All You Need to Know About React Hooks
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro