DEV Community


Posted on

How to store a function using React.useState

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();

  return (
    <button type="button" onClick={handleClick}>
      A button
Enter fullscreen mode Exit fullscreen mode

Things seem alright at first glimpse. However when I run it, I found out that the callback function was invoked immediately.


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);
Enter fullscreen mode Exit fullscreen mode

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.


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);
Enter fullscreen mode Exit fullscreen mode

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)

fellypsantos profile image
Fellyp Santos

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)

mehbubrashid profile image
Mehbub Rashid

Faced the same issue..after reading your post now i know why it didnt work as i expected :D thanks