I'm building a web app in React connected to Firebase, which authenticates users and stores post data. There seems to be a lot of documentation online about using Redux, but not a whole lot on persisting state without it.
When a user refreshes a page, the <App />'s State is reset, so I need to preserve the existing state/retrieve it from Firebase. Some articles suggest using local storage to store state. But with best practices in mind, what should be stored in local storage? My app stores all it's state in <App />, and passes down needed state as props to relevant components.
The following two examples assume a user has authenticated already and has just refreshed their page. We want their session to be preserved, so do we:
Example #1:
- App loads and checks local storage for a stringified object of the last stored local state. Sets the state to either that or empty state.
- If
'state'is retrieved and set, usethis.state['uid']to sync state with Firebase (fetching), then update local storage state again. - Whenever a user updates something, update the state (which updates Firebase) and also update the local storage state.
- When user logs out, clear the local storage
'state'item.
Example #2:
- App loads and checks local storage for a uid (which is set during authentication), if one is found, uses that to sync state with firebase (fetch).
- If a user reloads a page, data is fetched again from Firebase.
- When user logs out, clear the local storage
'uid'item.
With the first example, I'm effectively keeping two copies of the state. One in React's State, and another in the browser's Local Storage. In case the user closes the window or refreshes the page.
My question is: Which is the best practice?
or, is building a React app that needs to persist user and state across different routes without Redux totally bonkers?
Learning React is enough of a curve without Redux, so I'm trying to see if I can manage without it.