Declare an custom hook:
const useTest = (init: any) => {
const [arr, setArr] = useState<any[]>([]);
useEffect(() => {
setArr(Array.from(init.arr));
}, [init]);
return arr;
};
Use it:
useTest({ arr: [1] })
No matter what object or array did I pass to the init.arr, it would cause a infinite loop. I tried to wrap the init
object by useMemo, it`s useless. But if i pass a (string | number | null | undefined), it won`t get error.
I test it use '@testing-library/react-hooks' with jest. What`s more it only occur in my test case, but runs well in browser.
So what cause that?
you need to pass }, []);
as shown below to load useffect only once when component is loaded. it also should remove any infinite loop problems
React.useEffect(() => {
setArr(Array.from(init.arr));
}, []);
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.