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>;
}
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.