2021年1月26日星期二

useEffect vs state's setter function

In functional components, I have some state object data and I update it via setData() call.

If I have someFunction() that i need to call after setting the data variable (so I'm still in the same render cycle) is my only option to put that function in a useEffect hook?

I believe i can also use state's setter function as well? Like below:

const [data, setData] = useState({});    //set state variable  setData({key1: value1, key2:value2})    //....other code...  //next, i need to call `someFunction()` that needs to use the latest `data` state object    setData(data => {            //do whatever someFunction() is supposed to do        return data;  })  

When would one decide to use useEffect hook vs a setter function like this? Any major drawbacks? How do these two approaches differ?

ps I know the setter function is supposed to be used to set the new value when there is some kind of dependency on the previous value (like incrementing, etc) and what I'm doing is just setting it to the original value.

https://stackoverflow.com/questions/65911526/useeffect-vs-states-setter-function January 27, 2021 at 09:07AM

没有评论:

发表评论