Skip to content
Daishi Kato edited this page Mar 17, 2019 · 1 revision

Persistence Tips

If you want to persist and rehydrate changes of the state. Full Example

Quickstart

  1. Define a storage key
const persistenceKey = 'my_cool_app_persistence'
  1. Replace Reducer This will save the changes into localstorage.
// Before
export const { GlobalStateProvider, dispatch, useGlobalState } = createStore(myReducer, initialState)


// After
const persistentReducer = (state, action) => {
	const mutated = myReducer(state, action)
	localStorage.setItem(persistenceKey, JSON.stringify(mutated))
	return mutated
}
export const { GlobalStateProvider, dispatch, useGlobalState } = createStore(persistentReducer, initialState)
  1. Rehydrate on startup
// Before
const initialState = { counter: 0 }


// After
const firstState = { counter: 0 }

const initialStringFromStorage = localStorage.getItem(persistenceKey)
const initialState = initialStringFromStorage === null
	? firstState
	: JSON.parse(initialStringFromStorage)

Done 🚀

Clone this wiki locally