I am new to React, so apologies about the probably simple question.
Assume I have the following code:
const myComponent = () => {
const [someVar, setSomeVar] = useState(0);
// Other code
useEffect(() => {
// Do something
}, [someVar]);
return (
<button>Hello</button>
)
}
Everything is great so far, and whenever someVar
changes useEffect runs.
Now, is it possible to do the following?
const myComponent = () => {
const [someVar, setSomeVar] = useState(0);
// Other code
useEffect(() => {
// Do something
}, [<button with ID helloButton clicked>]); // <--------- this is what I want
return (
<button
id="helloButton"
onClick={() => {
// Do on click related stuff
}}
>
Hello
</button>
)
}
As you can see in the pseudo-code above, I want useEffect to be triggered by detecting the user clicked the button that has ID helloButton
Is this possible?
3
Answers
Well, the most obvious solution to me is that you move the content of the
useEffect
to a function and call this function on click:Now, if for some reason you don’t want to do that, you can also use a state that you will change on click, and pass it in the dependency array of your
useEffect
. For example:This looks like a use case for the useCallback hook
Something like the following snippet?
In short, it gets the element id from
e.target.id
and sets it tostate
.Inside of the
useEffect
we conditionally check if theid
fromstate
is equal to theelement id
and if this condition istruthy
we then trigger the call there.When the component will unmount
return () => {}
we set the value again to0
to avoid infinite loops.There are many ways to achieve the same, for instance, using the
useRef
hook. It can vary depending of the case.I hope it makes sense.
You can play around if you will codesandbox-io