astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.17k stars 41 forks source link

usage with reducer #54

Closed SimonVanherweghe closed 2 years ago

SimonVanherweghe commented 2 years ago

I'm not entirely sure this is something use-local-storage-state or just plain React related, but maybe someone can help me out here. I would like to manage my state with a reducer and keep that in sync with the localStorage.

I've stumbled up this article witch brought me to the idea of a "wrap" reducer so make sure any change on the state is synced to the localStorage.

So I altered the example with the approach mentioned to this: https://codesandbox.io/s/use-local-storage-state-with-reducer-cjs8iw?file=/src/App.js

But there is an issue. It is possible to set additional items in the localStorage, but when you refresh te page, they aren't displayed. When you have a look at the console, you will see 2 log statements. The second one has all the todo items, but they aren't set to my reducer state somehow. Any thoughts on this?

astoilkov commented 2 years ago

Hey, I'll explain what happens.

If you remove ssr: true the issue is gone. So let me explain why ssr: true breaks the code.

In React 17, a good implementation for SSR isn't possible, so I've done a little hack to make it work — the hook renders twice on initial load. That's also what's causing the problem.

useLocalStorageState() first renders with the default value and then with the value from local storage. However, the useReducer initializes itself with the default value and then doesn't change. This results in todos having the correct value but state having the default value.

Possible solutions:

SimonVanherweghe commented 2 years ago

Oh great, thanks for the explanation.

Turns out that some other deps supported React 18 in the meanwhile, so let's goooo! :-)