简体   繁体   中英

How to execute the function only after state changed in the caller (some callback) without useEffect in React functional component?

In a class component it's pretty easy to provide the desired order. If the state changes we always know when it really changed:

setState(updater[, callback])

From the documentation: "setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied."

I need to execute a function with 100% guarantee after some state variable change and I need it to be done at the caller (because sometimes I don't need to call the function, so I can't useEffect here). Something like that:

setVar(10);
callFuncHere(); // <======= No guarantee var == 10 at the moment

I see there are a lot of similar questions. But NONE of them has an appropriate solution. People suggest using useEffect but they don't think it's a different story.

I tried different solutions but nothing worked. Then I came to the direct brutal solution: I'm just using the global variable defined outside of the component. Then I can add the logic to useEffect and call or not call some specific function:

var flag = false;

useEffect(() => {
        if (flag){
            callFUnc();
            flag = false;
        }
    }, [someVar]);

...

flag = true;
setVar(newVal)

I hope this solution will help someone. What I wonder is WHY nobody in Facebook.React doesn't see the difference between a callback in setState and useEffect??

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