简体   繁体   中英

Question related to previous state implementation using react hooks

This is how the react's website suggests the implementation:

https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state

My question is, can we use useState instead of useRef ?

If yes, will it be any different from the useRef implementation?

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

function usePrevious(value) {
  // can we use "useState" instead of "useRef" here?
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

You can , eg

function Counter() {
  const [count, setCount] = useState(0);
  const [prevCount, setPrevCount] = useState();
  const setCountAndPrev = (newCount) => {
    setCount(newCount);
    setPrevCount(count);
  };

and then proceed to use setCountAndPrev (extract the whole thing into another hook if you want) - but it's a tiny bit convoluted.

If both state are not set at once, it could be inefficient since state setting results in re-renders, which should be avoided when not necessary. It's usually not a problem, but it might be considered more elegant.

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