I am learning React and currently having difficulties understanding how useEffect really supposed to work. What I am trying to accomplish is to make useEffect execute when the object it 'listens' to changes, but it doesn't happen.
I.e. according to the following tutorial https://www.tutorialspoint.com/using-useeffect-in-react-js-functional-component :
We can pass a second argument to useEffect, if there is any change on the second argument then React will execute this useEffect function call.
So here's my code, in which counter is the second argument/the object useEffect "listens" to:
function CounterUseRef() {
const counter = useRef(0);
function handleClick() {
counter.current = counter.current + 1;
console.log(counter.current);
}
useEffect(() => {
console.log("useEffect");
},
[counter.current]
//[counter]
);
return (
<div>
<h1>Counter {counter.current}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
}
export default CounterUseRef;
When the button is clicked, handleClick()
gets executed and counter.current
gets incremented, so I thought this would constitute "any change on the second argument".
However, setEffect
doesn't get executed. It doesn't get executed even if I make counter.current
itself the second argument.
Would really appreciate any help.
P.S. I do realize for a use case like this, useState
should have been used instead. What I really trying to figure out why useEffect
is not working.
always displays 0. Changing a ref doesn't cause a rerender, only updating props or state does that. And effects can only run after a render.
– Robin Zigmond Mar 16 '21 at 20:32