Blog>
Snippets

Inter-Process State Synchronization

Provide a code snippet that demonstrates how to synchronize Redux state between the main and renderer process using Electron's IPC mechanism.
const { ipcMain } = require('electron');
const { createStore } = require('redux');
const rootReducer = require('./reducers');

// Create Redux store in main process
const store = createStore(rootReducer);

// Handler to dispatch actions received from the renderer process
ipcMain.on('dispatch', (event, action) => {
  store.dispatch(action);
});

// Subscribe to the store to send state updates to renderer process
cstore.subscribe(() => {
  win.webContents.send('state-update', store.getState());
});
In the main process, we create a Redux store using our root reducer. We listen for 'dispatch' actions sent from the renderer process via IPC. When an action is received, it is dispatched to the store. The main process subscribes to the store's changes and sends the updated state back to the renderer process using IPC.
const { ipcRenderer } = require('electron');
const { createStore, applyMiddleware } = require('redux');
const rootReducer = require('./reducers');

// Middleware to send actions to main process
const forwardToMain = store => next => action => {
  ipcRenderer.send('dispatch', action);
  return next(action);
};

// Create Redux store in renderer process with middleware
const store = createStore(rootReducer, applyMiddleware(forwardToMain));

// Receive state updates from the main process
ipcRenderer.on('state-update', (event, newState) => {
  store.dispatch({ type: 'SET_ENTIRE_STATE', payload: newState });
});
In the renderer process, we set up a Redux store with a middleware to forward actions to the main process via IPC. We also listen for 'state-update' events received from the main process to synchronize the state. An action of type 'SET_ENTIRE_STATE' is used to replace the entire state of the renderer's store with the new state received.
const initialState = {};

// Example root reducer handling 'SET_ENTIRE_STATE'
function rootReducer(state = initialState, action) {
  if (action.type === 'SET_ENTIRE_STATE') {
    return action.payload;
  }
  // Handle other actions or return current state
  return state;
}
Root reducer example with a case for handling 'SET_ENTIRE_STATE' action, which replaces the entire state with the payload provided. This is to be used in conjunction with the IPC synchronization logic.