Sometimes things that have seen too easy to accomplish fail silently. Recently I have faced with such issue when I try to store a function in a React component to use it later. In this post, I have tried to explain my situation an its solution.
I was refactoring an old class-based React component into a functional one. I have tried to use useState
hook as it usually happens. But it this case I was trying to store a function.
import React, { useState } from "react";
const MyComponent = (props) => {
const [myFunc, setMyFunc] = useState();
const handleClick = () => {
const callback = props.someFunctionCall();
setMyFunc(callback);
};
return (
<button type="button" onClick={handleClick}>
A button
</button>
);
};
Things seem alright at first glimpse. However when I run it, I found out that the callback function was invoked immediately.
Why?
The code seems straightforward enough. But it took a couple of minutes to realize my mistake. It is because update function of useState
accepts either a value or a function to return a value:
type SetStateAction<S> = S | ((prevState: S) => S);
That's why when I passed a function to setMyFunc
, React tried to get the return value of callback
function by passing prevState
to it as an argument.
Solution
Once you realize the problem, it is easier to solve. All we need is an arrow function to wrap our actual callback
function:
setMyFunc(() => callback);
By doing that, we give React a function to get our callback
function and set it properly.
You can refer to React's Hooks API Reference to find more info about it.
Top comments (2)
I've created an account just to thank you!! I was struggling in create a feature when I should store a function to be executed later, tried everything and you save my code, love u. (now that I understand the problem, looks so obvius)
Faced the same issue..after reading your post now i know why it didnt work as i expected :D thanks