Reputation: 11
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
Reputation: 474
try
return {
increase: () => setCounter(count + 1),
decrease: () => setCounter(count - 1),
...
};
Upvotes: 3