简体   繁体   中英

Can you make useEffect run only once when one of the dependencies changes but not if it changes again?

I am rendering conditional content and I have

const [content,setContent] = useState(0);
const [data,setData] = useState([]);
let render;
switch(content)
{ 
  case 0:render=<Something/>; break;
  case 1:render=<Else/> ;break;  
}

I have some data which will be used only if we render <Else/> but the user can switch between <Something> and <Else/> with a radio button anytime. I don't want to load the data if users never switches to <Else/> , but I also don't want to load data again in case he switches from <Else/> to <Something/> and then again to <Else/>

so using useEffect(()=>{loadData().then(response=>setData(response.data))},[content]) not good idea since it will run everytime the user switches, but if I use useEffect(()=>{loadData().then(response=>setData(response.data))},[]) and user never switched to I loaded unnecessary data? How can I avoid this problem?

What you can do it's validate inside the useEffect hook if the data you need was already loaded. If that's the case, then just avoid making the request.

Or

Pass the responsability of fetch the data to the child components ( Else and Something ). That way it will only be executed when that component it's rendered.

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