Categories
JavaScript Answers

How to fix useState not triggering re-render with React?

Spread the love

Sometimes, we want to fix useState not triggering re-render with React.

In this article, we’ll look at how to fix useState not triggering re-render with React.

How to fix useState not triggering re-render with React?

To fix useState not triggering re-render with React, we should make a copy of objects or arrays before we update them.

For instance, we write

import React, { useState, useEffect } from "react";

const Comp = () => {
  //...
  const [state, setState] = {};

  const f = () => {
    setState({ ...state });
  };
  //...
};

to call setState with a copy of state in the function f to trigger re-rendering of the Comp component.

Conclusion

To fix useState not triggering re-render with React, we should make a copy of objects or arrays before we update them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *