Blog>
Snippets

Setting up Electron with Redux

Show how to install and configure Electron with Redux by creating a simple Redux store and integrating it within the Electron main process.
// Install required packages for Redux in Electron
// Run in terminal:
// npm install redux react-redux
Installs Redux and React-Redux NPM packages required for state management.
const { createStore, combineReducers } = require('redux');
const electron = require('electron');
const { ipcMain } = electron;

// Define initial state and reducer
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
  switch(action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// Combine reducers if there's more than one
const rootReducer = combineReducers({
  counter: counterReducer
});

// Create Redux store
const store = createStore(rootReducer);
Sets up a simple Redux store with a counter reducer. This is done in the main process of the Electron app.
// Handle state changes from renderer processes
ipcMain.on('increment', () => {
  store.dispatch({ type: 'INCREMENT' });
});

ipcMain.on('decrement', () => {
  store.dispatch({ type: 'DECREMENT' });
});
Sets up IPC listeners in the main process to increment and decrement the count via dispatched actions from renderer processes.
// Subscribe to store to listen for state changes
store.subscribe(() => {
  // Send updated state to the renderer process
  electron.webContents.getAllWebContents().forEach((webContents) => {
    webContents.send('state-update', store.getState());
  })
});
Subscribes to the store and sends the updated state to the renderer process whenever there is a state change.