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
JavaScript
x
17
17
1
const useRandomIs5x = () => {
2
const [state, setState] = useState(0);
3
useEffect(() => {
4
const t0 = setInterval(() => {
5
setState(getRandomValue())
6
}, 1000)
7
return () => clearInterval(to)
8
}, [])
9
return state % 5 === 0;
10
}
11
12
13
const Root = () => {
14
const bool = useRandomIs5x();
15
console.log("I'm re-rendering every second", bool)
16
return <div>test</div>
17
}
Advertisement
Answer
I could fix that issue using this library react-hooks-in-callback isolating the hook from the component.
check this sandbox example