I have an app using Redux. Is stores the global state as shown below:
Create Store:
import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
const configureStore = initialState => {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
};
export default configureStore;
Handles Local Storage
const storageName = 'xxxState';
export const loadState = () => {
try {
const serializedState = localStorage.getItem(storageName);
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch(err) {
return undefined;
}
};
export const saveState = state => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem(storageName, serializedState);
} catch(err) {
throw err;
}
};
Finaly starts the app session:
import React from 'react';
import ReactDOM from 'react-dom';
import Start from './start';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import { loadState, saveState } from './store/localStorage';
import throttle from 'lodash/throttle';
const persistedState = loadState();
const store = configureStore(persistedState);
store.subscribe(throttle(() => {
saveState(store.getState());
}, 1000));
ReactDOM.render(
<Provider store={store}>
<Start />
</Provider>,
document.getElementById('root'));
It works perfectly. So my question is: Is there any possibility to do the same with the new React Context API?
I am pretty confortable using the new context, I just want to know about store, localstorage, subscribe. So the the state is persisted even when the user leaves the app.