Mark As Completed Discussion

Setting up Redux

To configure Redux in a frontend project, follow these steps:

Step 1: Install Redux

Use npm to install the Redux library:

SNIPPET
1npm install redux

Step 2: Create the Redux Store

Import the createStore function from the Redux library and define the initial state and reducer function:

JAVASCRIPT
1const { createStore } = require('redux');
2
3const initialState = {
4  count: 0,
5};
6
7function reducer(state = initialState, action) {
8  switch (action.type) {
9    case 'INCREMENT':
10      return {
11        ...state,
12        count: state.count + 1,
13      };
14    case 'DECREMENT':
15      return {
16        ...state,
17        count: state.count - 1,
18      };
19    default:
20      return state;
21  }
22}
23
24const store = createStore(reducer);

Step 3: Connect Redux to React

Use the Provider component from the react-redux library to wrap your root component and provide access to the Redux store:

JAVASCRIPT
1import { Provider } from 'react-redux';
2
3ReactDOM.render(
4  <Provider store={store}>
5    <App />
6  </Provider>,
7  document.getElementById('root')
8);
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment