'React reset useMemo value

I need to reset the useMemo value in my react app but Im not sure how to do it. I made a minimal example of the setup. Basically when the reset button is click, the countDetails value needs to be null.

export default function App() {
  const [count, setCount] = React.useState(0);

  const countDetails = React.useMemo(() => {
    if(count === 0) {
      return {
        data: [],
        key: 'index'
      }
    }


    return {
      data: ['hi'],
      key: 'index'
    }
  }, [count]);

  console.log(count, countDetails);

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
      <button onClick={() => setCount(count + 1)}>Count</button>
      <button>Reset</button> 
    </div>
  );
}

Here is the code to editor. Im not sure how to do this because when the reset button is click the count variable doenst matter. So the useMemo wont update. This is a minimal example I tried to make. My app is more complex and I cant use a flag of setting the count to 9999 or something then in the useMemo check if count === 9999 then return null. is there a better way to do this?



Solution 1:[1]

    const [count, setCount] = React.useState(0);
    let countArr = React.useMemo(() => {
    if (count === 0) {
      return {
        data: [],
        key: "index",
      };
    }

   return {
      data: ["hi"],
      key: "index",
    };
  }, [count]);

  console.log(count, countArr);
  const resetHandler = () => {
    countArr = null;
    console.log(countArr);
  };
  return (
    <div>
      <h1>Hello StackBltz!</h1>
      <p>Start editing to see some magic happen :)</p>
      <button onClick={() => setCount(count + 1)}>Count</button>
      <button onClick={resetHandler}>Reset </button>
    </div>
  );

Solution 2:[2]

<button onClick={() => setCount(0)}>Reset</button> 

Your useMemo is directly dependent on the count coming from useState. I hope I understand you correctly that in your case, resetting means going back to zero. If that is the case, the code above does exactly that, it resets the count back to zero.

Solution 3:[3]

Set the count to 0

<div>
  <h1>Hello StackBltz!</h1>
  <p>Start editing to see some magic happen :)</p>
  <button onClick={() => setCount(count + 1)}>Count</button>
  <button onClick={() => setCount(0)}>Reset </button>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin
Solution 2 Jakub Kotrs
Solution 3 Dharman