Blog>
Snippets

Batch dispatching actions

Show how to batch multiple dispatch calls to prevent unnecessary re-renders and improve performance.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Batch Dispatching Example</title>
    <style>
        /* Add your CSS styling here. */
    </style>
</head>
<body>
    <div id="app"></div>

    <script>
        // Assuming we are using Redux as our state management

        // Action creator functions
        function actionOne(payload) {
            return { type: 'ACTION_ONE', payload };
        }

        function actionTwo(payload) {
            return { type: 'ACTION_TWO', payload };
        }

        // Batch dispatch function
        function batchDispatch(actions) {
            return (dispatch) => {
                actions.forEach(action => dispatch(action));
            };
        }

        // Example Redux store (needs redux-thunk for the batchDispatch to work)
        // const store = createStore(reducer, applyMiddleware(thunk));

        // Batch dispatch invocation
        store.dispatch(batchDispatch([
            actionOne({ data: 'data for action one' }),
            actionTwo({ data: 'data for action two' })
        ]));
    </script>
</body>
</html>
This HTML file includes an example of batch dispatching actions using Redux. The JavaScript script section defines action creator functions and a `batchDispatch` function, which takes an array of actions and dispatches them in a loop to prevent multiple re-renders. In this example, Redux would need to be set up with middleware like redux-thunk to handle the dispatched function.