Blog>
Snippets

Partial Redux State Synchronization

Show how to implement an action in Redux that selectively syncs only part of the application state across devices, to minimize data transfer and improve performance.
const syncPartialState = partialData => ({
    type: 'SYNC_PARTIAL_STATE',
    payload: partialData
});
Action creator function that creates an action to sync partial state. It expects partialData as a parameter, which is part of the state that needs to be synchronized.
const initialState = {
    user: {},
    settings: {},
    // other state slices
};

function rootReducer(state = initialState, action) {
    switch (action.type) {
        case 'SYNC_PARTIAL_STATE':
            return {
                ...state,
                ...action.payload
            };
        // handle other actions
        default:
            return state;
    }
}
Root reducer function that manages the state of the entire application. It handles 'SYNC_PARTIAL_STATE' action to merge the payload containing the partial state with the current state.
const store = Redux.createStore(rootReducer);

function syncStateWithServer(state) {
    // sync with server logic
}

store.subscribe(() => {
    const state = store.getState();
    const partialData = {
        settings: state.settings
        // select only the parts of state you want to sync
    };
    syncStateWithServer(partialData);
});
Subscribe to the store to listen for changes. On any state update, select only the parts of the app state that need to be synchronized and call the function that handles syncing with the server.