I'm trying to use new React hooks capabilities, but stumbled a bit.
I have a useEffect
which calls setInterval
, which updates local state. Like this:
const [counter, setCounter] = React.useState(0);
React.useEffect(() => {
const k = setInterval(() => {
setCounter(counter + 1);
}, 1000);
return () => clearInterval(k);
}, []);
return (
<div>Counter via state: {counter}<br/></div>
);
It doesn't work right, because counter is captured on first call and so counter is stuck at 1
value.
If i use refs, ref is updated, but rerender is not called (will only see 0 value in UI):
const counterRef = React.useRef(0);
React.useEffect(() => {
const k = setInterval(() => {
counterRef.current += 1;
}, 1000);
return () => clearInterval(k);
}, []);
return (
<div>Counter via ref: {counterRef.current}</div>
);
I can make what i want by combining them, but it really doesn't look right:
const [counter, setCounter] = React.useState(0);
const counterRef = React.useRef(0);
React.useEffect(() => {
const k = setInterval(() => {
setCounter(counterRef.current + 1);
counterRef.current += 1;
}, 1000);
return () => clearInterval(k);
}, []);
return (
<div>Counter via both: {counter}</div>
);
Could you please tell who to handle such cases properly with hooks?