Skip to content

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

Open
@btimo

Description

@btimo

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions