简体   繁体   中英

React hook only when props change?

useEffect(() => {
  // do something
}, [stringProp]);

stringProp is by default an empty string.

When I change stringProp to foobar the effect runs.

But,

the useEffect also runs when the component first mounts, which I don't want.

How to run an effect hook ONLY when props change?

You can not stop useEffect run when the component first mounted, but you can do the condition checking to run your code inside it like this:

useEffect(() => {
  // Only run when stringProp has value, you might have different condition, add them there
  if(stringProp){
    // do something
  }
}, [stringProp]);

Updated: If you might set stringProp back to the initial value, you can do use useRef to control first time run like this

const isFirstTimeOfUseEffect = useRef(true)
useEffect(() => {
  // Only run when stringProp has value, you might have different condition, add them there
  if(!firstUseEffectRun.current){
    // do something
  }else{
    firstUseEffectRun.current = false
  }
}, [stringProp]);

I've solved this problem many times using a ref

const firstRun = useRef(true);
...
useEffect(() => {
  // skip the first run
  if (firstRun.current) {
    firstRun.current = false;
    return;
  }

  // do stuff
}, [stringProp]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM