简体   繁体   中英

Can I use useRef Hook can also be used to keep track of previous state values

Already use useState, and useEffect to keep track of the previous state. Can I use useRef Hook can also be used to keep track of previous state values.

I belive you can use the useRef to keep track of pervious state value Check the code example below You can refer this artical https://blog.logrocket.com/accessing-previous-props-state-react-hooks/

   function Counter() {
  const [count, setCount] = useState(0);
//the useRef Hook allows you to persist data between renders
  const prevCountRef = useRef();
  useEffect(() => {
    //assign the ref's current value to the count Hook
    prevCountRef.current = count;
  }, [count]); //run this code when the value of count changes
  return (
    <h1>
      Now: {count}, before: {prevCountRef.current}
      {/*Increment  */}
      <button onClick={() => setCount((count) => count + 1)}>Increment</button>
    </h1>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM