Stumbled across this question and noticed the top answer is outdated with componentDidUpdate
, etc. I solved this using "@reduxjs/toolkit": "^1.8.4"
and "react-redux": "^8.0.2"
as follows:
For my redux store:
import { configureStore } from '@reduxjs/toolkit';
import { loadState, saveState, REDUX_KEY } from '../common';
import createReducer from './reducers'; // createReducer from '@reduxjs/toolkit
const store = configureStore({
reducer: createReducer,
preloadedState: loadState(REDUX_KEY), // loadState: JSON.parse() of store saved in localStorage
});
store.subscribe(() => saveState(REDUX_KEY, store.getState())); // saveState: JSON.stringify() and saves store to localStorage
export default store;
My index.tsx:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import Application from './app';
import store from './redux/store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Application />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
);
And then in a (usually top-level) application component in which I wanted to watch for changes in the redux store, I would have something like:
import React from 'react';
import { useSelector } from 'react-redux';
import { selectLoginStatus } './redux/selectors';
function LoginWatcher() {
const loginStatus = useSelector(selectLoginStatus);
// watch login status
React.useEffect(() => {
// perform action here when the state of 'status' updates
}, [loginStatus]);
return null;
}