DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
sarioglu
sarioglu

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();
    setMyFunc(callback);
  };

  return (
    <button type="button" onClick={handleClick}>
      A button
    </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.

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

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

Collapse
 
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

Must read for JS devs:

"I made 10x faster JSON.stringify() functions, even type safe"