实现一个useState的回调的hook

41 阅读1分钟

export const useStateCb = (init: any) => {
const [count, setCount] = useState(init);
const ref: any = useRef();
useEffect(() => {
ref.current && ref.current(count);
}, [count]);

const mySetCount = (value: any, cb: any) => { setCount(value); ref.current = cb; }; return [count, mySetCount];};
const [a, setACb] = useStateCb(1);
setACb(2, (b) => { console.log(b);});