Blog>
Snippets

Immutable State Management

Leverage libraries like Immer in reducers to work with the Redux store's state in a type-safe manner, preventing accidental mutations and type inconsistencies.
import { createStore } from 'redux';
import produce from 'immer';

// Example state
const initialState = {
    user: {
        name: 'Anonymous',
        preferences: {}
    }
};

// Action Types
const UPDATE_USER_NAME = 'UPDATE_USER_NAME';

// Action Creators
function updateUserName(newName) {
    return {
        type: UPDATE_USER_NAME,
        payload: newName
    };
}

// Reducer with Immer for immutability
const rootReducer = produce((draft, action) => {
    switch (action.type) {
        case UPDATE_USER_NAME:
            draft.user.name = action.payload;
            break;
        // You can handle other actions here
    }
}, initialState);

// Store creation
const store = createStore(rootReducer);

// Dispatch an action to update state
store.dispatch(updateUserName('John Doe'));
This code sets up a Redux store with an initial state and a single action to update a user's name. It uses Immer's produce function to enforce immutable state management within the reducer.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Immutable State Management</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/immer/9.0.6/immer.umd.js"></script>
</head>
<body>
    <div id="app">
        <!-- This is where your React components would go in a real app -->
        <h1>User Name: <span id="userNameDisplay">Anonymous</span></h1>
        <button id="updateUserNameBtn">Change User Name</button>
    </div>
    <script src="./app.js"></script>
</body>
</html>
This is the HTML template that contains a simple UI for displaying the user's name and a button to trigger the name change. The actual state management is handled in the linked JavaScript file 'app.js'. The script tags include Redux and Immer libraries.
document.getElementById('updateUserNameBtn').addEventListener('click', function() {
    // This could trigger a new action dispatch in your actual implementation
    store.dispatch(updateUserName('Jane Smith'));
    document.getElementById('userNameDisplay').textContent = store.getState().user.name;
});
This JavaScript code adds a click event listener to the button in the HTML template that dispatches the `updateUserName` action to the Redux store. Then it updates the displayed user's name in the HTML with the new value from the store's state.
body {
    font-family: Arial, sans-serif;
}

#app {
    text-align: center;
    margin-top: 20px;
}

button {
    padding: 10px 15px;
    font-size: 16px;
}
This CSS defines the basic styles for the HTML template. It includes font styles, alignment, and button styling to make the simple UI more visually appealing.