imagine to have this hook that changes his value every second and returns true if the random value is a multiple of 5 otherwise false. what can I do to stop re-rendering every second?
PS: I tried useMemo, and useRef to return back always the same object but it’s still re-rendering.
please help
const useRandomIs5x = () => {
const [state, setState] = useState(0);
useEffect(() => {
const t0 = setInterval(() => {
setState(getRandomValue())
}, 1000)
return () => clearInterval(to)
}, [])
return state % 5 === 0;
}
const Root = () => {
const bool = useRandomIs5x();
console.log("I'm re-rendering every second", bool)
return <div>test</div>
}Advertisement
Answer
I could fix that issue using this library react-hooks-in-callback isolating the hook from the component.
check this sandbox example