React Redux is a popular library used to manage state in large-scale React applications. It combines the power of React with the predictability of Redux, making it easier to manage state and ensure that your application remains responsive and efficient.

Getting Started

Before diving into the details, let's quickly set up a new React project with Redux:

npx create-react-app react-redux-tutorial
cd react-redux-tutorial
npm install redux react-redux

Basics of Redux

Redux is a state management library that provides a centralized store for your application. It works on the principle of immutability and pure functions.

Actions

Actions are payloads of information that send data from your application to your store. They are the only way to change the state in Redux.

const ADD_TODO = 'ADD_TODO';

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  };
}

Reducers

Reducers are functions that take the current state and an action, and return the next state. They are pure functions, meaning they always return the same output for the same input.

const todos = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [...state, action.text];
    default:
      return state;
  }
};

Store

The store is the only place where your application's state is stored. It provides methods to read the state, dispatch actions, and subscribe to changes.

import { createStore } from 'redux';
import todos from './reducers';

const store = createStore(todos);

Integrating Redux with React

To integrate Redux with React, you can use the Provider component from react-redux. This component makes the Redux store available to any nested components that are using connect().

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')
);

Using Connect

connect() is a higher-order component that connects a React component to a Redux store. It provides the component with access to the store's state and allows it to dispatch actions.

import React from 'react';
import { connect } from 'react-redux';

const TodoList = ({ todos }) => (
  <ul>
    {todos.map((todo, index) => (
      <li key={index}>{todo}</li>
    ))}
  </ul>
);

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

export default connect(mapStateToProps)(TodoList);

Next Steps

For more detailed information and advanced usage, check out the official React Redux documentation.


React Redux Architecture