最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to trigger useEffect in React only once AFTER some certain variable gets loaded - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question asked Jul 1, 2021 at 17:24 user6792790user6792790 6881 gold badge9 silver badges26 bronze badges 3
  • 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
Add a ment  | 

1 Answer 1

Reset to default 7

You 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]);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论