简体   繁体   中英

React custom hook infinite loop

I tried to make a method using a custom react hook in order to reuse the same state logic in many components, but I got invariant violation "prevent infinite loop".

function useCounter(initial) {
  const [count, setCounter] = useState(initial);

  return {
    increase: setCounter(count + 1),
    decrease: setCounter(count - 1),
    count
  };
}

usage

import useCounter from "./useCounter";

function CompOne() {
  const { count, increase } = useCounter(0);

  return <div onClick={() => increase()}>Component {count}</div>;
}

demo https://codesandbox.io/s/practical-hooks-440l1

try

  return {
    increase: () => setCounter(count + 1),
    decrease: () => setCounter(count - 1),
    ...
  };

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