简体   繁体   中英

How to run a single useEffect both on re-render and on dependency change?

I have the following code,

 const [over, setOver] = useState(false); useEffect(() => { //some logic }, [over]);

and I want to be able to run the use effect when the (over) has been changed and also if component props changes as for now the code runs only when over has been changed, similar to

 useEffect(() => { //some logic }, []);

Your first code and second are not similar at all. Second one runs once only when the component is mounted (added to the DOM). And first code will run onComponentMount and onOverChange .

You need to understand react component lifecycle to understand how useEffect works.

There are 3 lifecycle events. onMount , onStateChange and onUnMount . The callback function runs when onMount or onStateChange is triggered. When you use [] it means the code will only run when mounted and not on any stateChange event. (Cause there isn't any state available to watch)

useEffect(() => {
  // this will run when component is added to the DOM or a dependency state have changed
  console.log("mounted or dependency state changed");
  
  // this will run when component is destroyed
  return () => console.log("component unmounted");
  
}, [dependency1, dependency2]);

One straightforward way to do this is add the props in dependency array

  useEffect(() => {
     //some logic
  }, [over,props]);

But that is not really a good idea

Go through this once You might not need an effect

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