streamich / react-use

React Hooks ā€” šŸ‘
http://streamich.github.io/react-use
The Unlicense
41.66k stars 3.14k forks source link

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

Open btimo opened 2 months ago

btimo commented 2 months ago

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:

akdlsz21 commented 2 months ago

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

I created a fix and posted a PR.