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

useStateWithHistory: initialState of function type are not handled correctly #2568

Open
btimo opened this issue Jul 16, 2024 · 1 comment · May be fixed by #2572
Open

useStateWithHistory: initialState of function type are not handled correctly #2568

btimo opened this issue Jul 16, 2024 · 1 comment · May be fixed by #2572

Comments

@btimo
Copy link

btimo commented Jul 16, 2024

What is the current behavior?
With the hook useStateWithHistory, when using a function for the initialState, the function is correctly called and its output returned as the first state value

But when using the back handler, the state returned is the function and not its output.

Steps to reproduce it and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have extra dependencies other than react-use. Paste the link to your JSFiddle or CodeSandbox example below:

https://codesandbox.io/p/sandbox/withered-sunset-gwjw8r

What is the expected behavior?

In case the initialState is a function, we should return its output, always, and not even store the function, as per the React Dev documentation stating this function should be triggered only once:

If you pass a function as initialState, it will be treated as an initializer function. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. See an example below.

A little about versions:

  • OS: N/A
  • Browser (vendor and version): N/A
  • React: N/A
  • react-use: latest
  • Did this worked in the previous package version?: No
@akdlsz21
Copy link

The issue seems to be that history saves the function itself rather than the result.

I created a fix and posted a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants