Blog>
Snippets

Importing Redux with ESM Syntax

Showcase the new way of importing Redux core functionalities using ECMAScript module syntax in a modern JavaScript environment.
import { createStore, applyMiddleware } from 'redux';

// Import reducers and middleware
import rootReducer from './reducers';
import loggerMiddleware from './middleware/logger';

// Create a Redux store with root reducer and middleware
const store = createStore(
    rootReducer,
    applyMiddleware(loggerMiddleware)
);

export default store;
This code imports the 'createStore' and 'applyMiddleware' functions from Redux using ESM syntax. It then imports the rootReducer and loggerMiddleware, and creates a store with these reducers and middleware. Finally, it exports the store as the default export.
import { useSelector, useDispatch } from 'react-redux';

// Use the useSelector hook to access state from the Redux store in a component
const count = useSelector(state => state.counter.value);
// Use the useDispatch hook to dispatch actions to the Redux store
const dispatch = useDispatch();
This code imports the 'useSelector' and 'useDispatch' hooks from 'react-redux' which are used to interact with the Redux store in a React component. The useSelector hook is used to access a specific value from the store's state, and useDispatch returns the dispatch function to send actions to the store.