How to Force Rerender With Hooks in React

How to Force Rerender With Hooks in React

Ferenc Almasi β€’ Last updated 2021 July 13 β€’ Read time 2 min read
  • twitter
  • facebook
React

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.

Copied to clipboard! Playground
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
    </button>
  );
};
useForceUpdate.js

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
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.