React Redux
Tags: redux, javascript, react, webdev
Published: 2024-06-14 06:26:21

When I started learning React Redux, I was confused about how to use Redux correctly. I understood how it works under the hood and its purpose as a state management library, but using **mapStateToProps** and **mapDispatchToProps** with the **connect** function was difficult for me due to the syntax. It always confused me. When the hook API, like **useSelector** and **useDispatch**, came out, I finally understood how to use Redux properly in functional components. Here, I'll explain it with code step by step.

## Step 1: Install Dependencies

First, ensure you have **redux**, **react-redux** installed in your project:

```
npm install redux react-redux 
```

## Step 2: Create the Redux Store

Create a file called **store.js** to set up the Redux store and reducer:

```
// store.js
import { createStore } from 'redux';

// Initial state
const initialState = {
  count: 0,
};

// Reducer function
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1,
      };
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1,
      };
    default:
      return state;
  }
};

// Create store
const store = createStore(reducer);

export default store;

```

## Step 3: Provide the Store to the App

Wrap your application with the **Provider** component from **react-redux** to make the Redux store available to the entire app:

```
// index.js or App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

```

## Step 4: Use Redux in Components

Using Hooks (**useSelector** and **useDispatch**)

Create a functional component and use the hooks **useSelector** and **useDispatch**:

1. **useSelecter** to show state data in component 
2. **useDispath** to manipulate the state with payload

```
// Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
};

export default Counter;

```

Using **connect** with Class Components

For a class component, you can use the **connect** function with **mapStateToProps** and **mapDispatchToProps**:

1. **mapStateToProps** (like **useSelecter**) return state and use in component
2. **mapDispatchToProps** (like **useDispath**) manipulate state

```
// ClassCounter.js
import React, { Component } from 'react';
import { connect } from 'react-redux';

class ClassCounter extends Component {
  render() {
    const { count, increment, decrement } = this.props;
    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={increment}>Increment</button>
        <button onClick={decrement}>Decrement</button>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  count: state.count,
});

const mapDispatchToProps = (dispatch) => ({
  increment: () => dispatch({ type: 'INCREMENT' }),
  decrement: () => dispatch({ type: 'DECREMENT' }),
});

export default connect(mapStateToProps, mapDispatchToProps)(ClassCounter);

```

## Step 5: Use the Components in Your App

Finally, use the components in your main application file:

```
// App.js
import React from 'react';
import Counter from './Counter';
import ClassCounter from './ClassCounter';

const App = () => (
  <div>
    <h1>Redux Example</h1>
    <Counter />
    <ClassCounter />
  </div>
);

export default App;

```

This setup covers both the use of hooks (**useSelector**, **useDispatch**) for functional components and the **connect** function for class components, providing a comprehensive example of how to manage state with Redux in a React application.