astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.09k stars 39 forks source link

Return isPossiblyHydrating #52

Closed saiichihashimoto closed 2 years ago

saiichihashimoto commented 2 years ago

There's no good way to be certain whether we're still hydrating or not, except for also keeping track of first render in our apps, which is not good. It would make sense to receive that is a value so we can use that within our "loading" states.

astoilkov commented 2 years ago

What do you think about that?

const _isFirstRenderRef = useRef(true)
const isFirstRender = _isFirstRenderRef.current
_isFirstRenderRef.current = false

I'm hesitant to provide this because I think it's possible to remove the variable altogether in the next release. However, I'm still not sure.

saiichihashimoto commented 2 years ago

The issue is specifically that I need to manage if your hook is "loading" on my own and I have to do it by managing copying how you're determining that, which is using a first render ref. The issue with your solution is that it's more an illustration of my problem rather than my solution. I don't want to maintain logic copying the internals of your hook's loading state that, if useLocalStorageState ever changes, will become incorrect and I'll never know. This hook should keep that logic internal and return a boolean to notify. Also, not sure how there's a solution to showing loading state at all, considering that SSR will always not have local state while client state will, meaning there always needs to be a state where there's no value and one following with data.

astoilkov commented 2 years ago

Ok. Got it. Let me see how the React 18 support implementation is going. I want for both React 17 and React 18 to have a unified API and I'm not sure if I will be able to have this variable in the React 18 implementation.

astoilkov commented 2 years ago

Ok. I'm done with the React 18 implementation. I won't implement the proposed property because React 18 have a way of knowing if you are hydrating or not, React 17 doesn't. This means that the API for the two versions will be different (isPossiblyHydrating in React 17, and isHydrating in Reat 18) and upgrading and consistency will suffer.

Additionally, I can actually guarantee that the logic for the React 17 (not React 18) won't change. There isn't any other way to determine if you are hydrating or not in React 17 rather than guessing that the first render is the hydration. That's highly unoptimal and in many cases untrue but that's why now in React 18 this problem has been solved.

Thanks for the feedback and sorry for not being able to help a lot. Closing this issue.