0

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
    }
}

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

1 Comment

useCallback is suited for the logic I'm writting. I ended up using useRef(); const buttonAction = useRef(null); SETTING buttonAction .current = () => createSubscription( a? b : c ); CALLING onClick={() => professionalButtonAction.current()} . Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.