Home > OS >  React reset useMemo value
React reset useMemo value

Time:03-31

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?

CodePudding user response:

    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>
  );

CodePudding user response:

<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.

CodePudding user response:

Setting the count to 0 dont solve your problem ?

<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>
  • Related