Understanding Redux: From Simple Explanation to Practical Example in React
Tags: react
Published: 2023-11-01 13:50:14

As someone constantly seeking new knowledge and understanding, I've always believed that the best way to learn is by diving deep and getting hands-on experience. That's precisely why I wanted to write this article. The concept of Redux, especially in the context of React, had always intrigued me. However, it was also one of those topics that seemed a bit daunting from the outside. So, I decided the best way to truly grasp it was to break it down, not just for others, but for myself as well. By explaining Redux in simple terms and then walking through a practical example step by step, I aimed to solidify my understanding and, hopefully, help others along the way. This article is a product of that learning journey, designed to take you from the basics of Redux to applying it in a React application, all through a path of self-exploration and knowledge building.

### What is Redux?

Imagine you have a small town with different buildings (like houses, a post office, a supermarket, etc.). This town is your application. Each building has its own set of rules and activities happening inside, much like different parts of your application (different components or pages) have their own states (data).

Now, what if all these buildings had to share some common information? For instance, a town announcement or a weather update. It would be inefficient for each building to manage this information separately. So, the town decides to build a central bulletin board in the main square. This board is like Redux.

Redux is essentially a centralized place to manage and store the shared state (data) of your application. It makes sure that this shared information is consistent and easily accessible to any part of your application that needs it.

### Key Concepts of Redux:

1. **Store**: This is the central bulletin board of the town. It's where the shared state of your application lives.
2. **Actions**: Suppose a new announcement needs to be made. In Redux, this is called an action. It's a simple message that describes what happened.
3. **Reducers**: These are like the town officials who decide how the bulletin board (store) should be updated based on the actions. They take the current state and an action, and return a new state.

### Example:

Imagine a simple application where users can like or dislike a post.

- **State**: The number of likes for the post.
- **Action**: Two actions can happen - "like" or "dislike".
- **Reducer**: It decides what happens to the state (number of likes) when an action is taken. For a "like" action, it increases the number of likes; for a "dislike", it decreases the number of likes.

Redux makes sure that any part of your application that needs to know about the number of likes can easily access this information and that this information is updated consistently across the application.

### Redux with React:

Let's create a simple React application that uses Redux. We'll build a counter application where users can increase, decrease, or reset the count.

### Step 1: Set Up Your Project

First, create a new React project if you haven't already:

```bash
npx create-react-app redux-counter
cd redux-counter
```

### Step 2: Install Redux

Install Redux and its React bindings:

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

### Step 3: Set Up Redux

1. **Create a Reducer**: 

Create a file named `counterReducer.js`. This reducer will handle the state of the counter.

```javascript
// src/counterReducer.js

const initialState = {
  value: 0,
};

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'counter/incremented':
      return { ...state, value: state.value + 1 };
    case 'counter/decremented':
      return { ...state, value: state.value - 1 };
    case 'counter/reset':
      return { ...state, value: 0 };
    default:
      return state;
  }
};

export default counterReducer;
```

2. **Create a Store**:

Create a file named `store.js`. This is where you'll set up your Redux store.

```javascript
// src/store.js

import { createStore } from 'redux';
import counterReducer from './counterReducer';

const store = createStore(counterReducer);

export default store;
```

### Step 4: Provide Redux Store to React

In your `index.js`, wrap your application in a `Provider` from `react-redux` and pass the store to it.

```javascript
// src/index.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(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
```

### Step 5: Create the React Component

In your `App.js`, create a simple counter component.

```javascript
// src/App.js

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

function App() {
  const count = useSelector((state) => state.value);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => dispatch({ type: 'counter/incremented' })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: 'counter/decremented' })}>
        Decrement
      </button>
      <button onClick={() => dispatch({ type: 'counter/reset' })}>
        Reset
      </button>
    </div>
  );
}

export default App;
```

### Step 6: Run Your Application

Now, run your application:

```bash
npm start
```

Your application should now have a simple counter with "Increment", "Decrement", and "Reset" buttons. Clicking these buttons will update the state in the Redux store, and the changes will be reflected in the component.

This is a basic example. As your application grows, you might want to explore more advanced Redux concepts like action creators, middleware, selectors, and tools like Redux Toolkit, which simplifies many Redux patterns.