Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass a function into useState in ReactJS #126

Open
namtx opened this issue Jun 11, 2021 · 0 comments
Open

How to pass a function into useState in ReactJS #126

namtx opened this issue Jun 11, 2021 · 0 comments
Labels

Comments

@namtx
Copy link
Owner

namtx commented Jun 11, 2021

Problem

As we already know, the Dispatch function from the useState hook accept a function as an async dispatcher. So, we can't pass a function into this dispatcher as expected. Example:

const [callback, setCallback] = useState<() => void>();
// then
setCallback(() => doSomething()); // ❌  we can't do this, as the returned value of `doSomething` will be pass into the `callback` value.

Solution

We need to pass a function that returns a function that returns a function 😂

const [callback, setCallback] = useState<() => void>();
// then
setCallback(() => () => doSomething());  // ✅ correct!
@namtx namtx added the ReactJS label Jun 11, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant