Jennifer
Jennifer

Reputation: 11

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

Upvotes: 0

Views: 90

Answers (1)

albert
albert

Reputation: 474

try

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

Upvotes: 3

Related Questions