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

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.