I am trying to use useEffect hook in React to trigger some functions only once. I know that this could normally be done by doing
useEffect(() => {
// some functions
}
}, [])
However, the functions require some values to be loaded. So, I only want this useEffect to get triggered only ONCE when the value is not empty.
useEffect(() => {
// some functions
}, [theValue])
This is what I tried, but I know that this will get triggered whenever theValue
changes.
How can I change my useEffect to run only ONCE when theValue
bees not empty?
I am trying to use useEffect hook in React to trigger some functions only once. I know that this could normally be done by doing
useEffect(() => {
// some functions
}
}, [])
However, the functions require some values to be loaded. So, I only want this useEffect to get triggered only ONCE when the value is not empty.
useEffect(() => {
// some functions
}, [theValue])
This is what I tried, but I know that this will get triggered whenever theValue
changes.
How can I change my useEffect to run only ONCE when theValue
bees not empty?
- 1 By "loaded" are you talking about an async request? – Andy Commented Jul 1, 2021 at 17:29
-
without any other info... what you could do is a third state that will "filter" everything after the first call... something inside useEffect like
if (firstTime) do stuff else dont
– Noriller Commented Jul 1, 2021 at 17:42 -
useEffect
is essentially discouraged. See react docs You might not need an effect – Mulan Commented Jan 13, 2023 at 14:16
1 Answer
Reset to default 7You can use a React ref to hold a boolean if the effect has been triggered yet, and bine that with a conditional test that all the dependencies have been met to trigger the effect.
const effectTriggeredRef = React.useRef(false);
React.useEffect(() => {
if (!effectTriggeredRef.current && /* deps conditions */) {
effectTriggeredRef.current = true;
// trigger some functions
}
}, [...deps]);