Home > OS >  js async function executed when referenced
js async function executed when referenced

Time:11-21

I'm trying to reference an async function but instead it gets executed.

const Payment = props => {
    const [buttonAction, setButtonAction] = useState(null);

    useEffect(() => {
        if(some true stuff){
            // this gets executed instead of being a reference to a function
            setButtonAction(() => createSubscription(a ? b : c ));
        }
    }, [deps...]);

    const createSubscription = async (sessionId) => {
        // code
    }
}

CodePudding user response:

React's useState setter functions accept either:

  • The data to set, or
  • A function to call with the most recent version of the data (see here in the documentation) that will return the data to set

By passing a function into setButtonAction, you're asking React to call that function with the most recent value of buttonAction so you can update it.

You can't directly store functions in state like that, and there's usually no reason to do so (though there are edge cases).

Some alternatives:

  • If you really need to store a function in state, wrap it in an object.
  • Use useCallback or useMemo to reuse a function, only updating it when its dependencies change
  • Keep it in a ref instead.
  • Related