Reputation: 2262
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
}
}
Upvotes: 0
Views: 34
Reputation: 1074168
React's useState
setter functions accept either:
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:
useCallback
or useMemo
to reuse a function, only updating it when its dependencies changeUpvotes: 4