Blog>
Snippets

Named Exports for Redux Action Creators

Provide an example of defining and exporting multiple Redux action creators using named exports with ESM syntax, and importing them in a component.
// actions.js
// Define action creators and export them
export const increment = () => {
    return {
        type: 'INCREMENT'
    };
};

export const decrement = () => {
    return {
        type: 'DECREMENT'
    };
};

export const reset = () => {
    return {
        type: 'RESET'
    };
};
This piece of code defines three Redux action creators: increment, decrement, and reset. Each action creator is a function that returns an action object with a type property. The actions are then exported using named exports, allowing them to be individually imported elsewhere.
// MyComponent.jsx
import React from 'react';
import { useDispatch } from 'react-redux';
import { increment, decrement, reset } from './actions';

const MyComponent = () => {
    const dispatch = useDispatch();

    const handleIncrement = () => {
        dispatch(increment());
    };

    const handleDecrement = () => {
        dispatch(decrement());
    };

    const handleReset = () => {
        dispatch(reset());
    };

    // Render buttons to dispatch the actions
    return (
        <div>
            <button onClick={handleIncrement}>Increment</button>
            <button onClick={handleDecrement}>Decrement</button>
            <button onClick={handleReset}>Reset</button>
        </div>
    );
};

export default MyComponent;
This code imports the previously exported action creators into a React component called MyComponent using named imports. We use the useDispatch hook from react-redux to get the dispatch function, which we then use to dispatch actions when handling button clicks. Each button is associated with one of the action creators.