Lesson 14-Deep Dive into the React Ecosystem React Redux Applications

Introduction to React Redux

React Redux Installation

React Redux 8.x requires React 16.8.3 or higher / React Native 0.59 or higher.

Creating a New React and Redux Application

Use Create React App with the official Redux+JS or Redux+TS template, which integrates Redux Toolkit and React Redux with React components.

# Redux + JavaScript Template
npx create-react-app my-app --template redux

# Redux + TypeScript Template
npx create-react-app my-app --template redux-typescript

Adding React Redux to an Existing React Application

# Using npm:
npm install react-redux

# Or using Yarn:
yarn add react-redux

Integrating Redux with UI

  1. Create a Redux store.
  2. Subscribe to updates.
  3. Inside the subscription callback:
  • Retrieve the current store state.
  • Extract the data needed for this UI section.
  • Update the UI with the data.
  1. If necessary, render the UI with the initial state.
  2. Respond to UI interactions by dispatching Redux actions.

Why Use React Redux?

Official Redux UI Binding for React

  • While Redux can work with any UI layer, it was originally designed for React. Other frameworks have UI bindings, but React Redux is maintained directly by the Redux team.
  • As the official Redux binding for React, React Redux stays updated with API changes from any library, ensuring your React components behave as expected. Its intended usage aligns with React’s design principles—writing declarative components.

Performance Optimization

  • React is generally fast, but by default, any component update causes React to re-render all components in that part of the component tree. If a component’s data hasn’t changed, re-rendering can waste performance, as the requested UI output remains the same.
  • To address performance issues, the best approach is to skip unnecessary re-renders, so components only re-render when their data changes. React Redux implements numerous internal performance optimizations to ensure your components re-render only when necessary.
  • By connecting multiple components in the React component tree, you can ensure each connected component extracts only the specific store state it needs. This reduces re-renders, as most of the time, the specific data hasn’t changed.

React Redux Basics

Getting Started

Creating a Redux Store

Create a file named src/app/store.js. Import the configureStore API from Redux Toolkit. Start by creating an empty Redux store and exporting it:

app/store.js

import { configureStore } from '@reduxjs/toolkit';

export default configureStore({
  reducer: {},
});

This creates a Redux store and automatically configures the Redux DevTools extension for inspecting the store during development.

Providing the Redux Store to React

After creating the store, make it available to React components by wrapping the application with a React Redux <Provider> in src/index.js. Import the Redux store, place a <Provider> around <App>, and pass the store as a prop:

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import store from './app/store';
import { Provider } from 'react-redux';

// Starting from React 18
const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

Creating a Redux State Slice

Create a new file named src/features/counter/counterSlice.js. Import the createSlice API from Redux Toolkit.

Creating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions to define state updates. After creating the slice, export the generated Redux action creators and the entire slice reducer function.

Redux requires immutable state updates by making copies of data and updating those copies. However, Redux Toolkit’s createSlice and createReducer APIs use Immer internally, allowing you to write mutating update logic that becomes correct immutable updates.

features/counter/counterSlice.js

import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows writing mutating logic in reducers.
      // It doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a draft state and produces a new immutable state based on those changes.
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

// Generate Action creators for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

Adding Slice Reducers to the Store

Import the reducer function from the counter slice and add it to the store. By defining a field in the reducers parameter, you instruct the store to use this slice reducer function to handle all updates to that state.

app/store.js

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
});

Using Redux State and Actions in React Components

Use React Redux hooks to let React components interact with the Redux store. Use useSelector to read data from the store and useDispatch to dispatch actions. Create a src/features/counter/Counter.js file containing a <Counter> component, then import and render it in App.js.

features/counter/Counter.js

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { decrement, increment } from './counterSlice';
import styles from './Counter.module.css';

export function Counter() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <div>
        <button
          aria-label="Increment value"
          onClick={() => dispatch(increment())}
        >
          Increment
        </button>
        <span>{count}</span>
        <button
          aria-label="Decrement value"
          onClick={() => dispatch(decrement())}
        >
          Decrement
        </button>
      </div>
    </div>
  );
}

Clicking the Increment and Decrement buttons:

  • Dispatches the corresponding Redux action to the store.
  • The counter slice reducer processes the actions and updates its state.
  • The <Counter> component sees the new state value from the store and re-renders with the updated data.
  • Creating a Redux store with configureStore
    configureStore accepts a reducer function as a named parameter.
    configureStore automatically sets up the store with good defaults.
  • Providing the Redux store to React components
    Wrap a React Redux <Provider> component around your <App />.
    Pass the Redux store as <Provider store={store}>.
  • Creating a Redux slice reducer with createSlice
    Call createSlice with a string name, initial state, and named reducer functions.
  • Reducer functions can use Immer for mutating state
    Export the generated slice reducer and action creators.
    Use React Redux useSelector/useDispatch hooks in React components.
    Use the useSelector hook to read data from the store.
    Use the useDispatch hook to get the dispatch function and dispatch actions as needed.

Integrating TypeScript with Redux Toolkit

Project Initialization

Create a new React project with Create React App and install the necessary dependencies.

npx create-react-app my-app --template typescript
cd my-app
npm install @reduxjs/toolkit react-redux

Configuring the Redux Store

Create a store folder in the src directory and add a store.ts file. Use Redux Toolkit’s configureStore to create the store.

store.ts

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice'; // Import the reducer created later

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

Creating a Slice

Create a counterSlice.ts file in the store folder. Use createSlice to implement a simple counter feature.

counterSlice.ts

import { createSlice } from '@reduxjs/toolkit';

interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

Connecting React Components to Redux

In your React components, use useSelector and useDispatch to access and manipulate the Redux store.

Counter.tsx

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from '../store/counterSlice';

const Counter: React.FC = () => {
  const count = useSelector((state: RootState) => state.counter.value);
  const dispatch = useDispatch<AppDispatch>();

  return (
    <div>
      <div>
        Count: {count}
      </div>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>Add 5</button>
    </div>
  );
};

export default Counter;

Setting Up Type-Safe Actions and State

Create a types.ts file in the store folder to define types for your state and actions.

types.ts

import { PayloadAction } from '@reduxjs/toolkit';

export interface CounterState {
  value: number;
}

export type AppThunk<ReturnType = void> = (
  dispatch: AppDispatch,
  getState: () => RootState,
  extraArg: ExtraArgument
) => ReturnType;

// Define a property on the store's `dispatch` type,
// which infers the dispatch type from the stores with the corresponding `createAsyncThunk` return type
export type AppDispatch = typeof store.dispatch & {
  [K in keyof AsyncThunkApi]: AsyncThunkApi[K] extends (
    ...args: infer Args
  ) => infer R
    ? (...args: Args) => R
    : never;
};

Using Thunk Middleware

For asynchronous operations like API calls, Redux Toolkit provides createAsyncThunk to handle these cases.

asyncActions.ts

import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const fetchCount = createAsyncThunk(
  'counter/fetchCount',
  async (amount: number) => {
    const response = await axios.get(`https://api.example.com/data/${amount}`);
    return response.data;
  }
);

Handling Thunks in Reducers

In your slice, use extraReducers to handle actions generated by createAsyncThunk.

counterSlice.ts (Updated)

// ... Previous code omitted ...

const extraReducers = (builder) => {
  builder.addCase(fetchCount.pending, (state) => {
    state.status = 'loading';
  });
  builder.addCase(fetchCount.fulfilled, (state, action: PayloadAction<number>) => {
    state.status = 'idle';
    state.value += action.payload;
  });
};

export const counterSlice = createSlice({
  // ... Previous code omitted ...
  extraReducers,
});

Using Thunks in Components

In your component, use useDispatch to call the thunk.

Counter.tsx (Updated)

// ... Previous code omitted ...

const dispatch = useDispatch<AppDispatch>();

const handleFetchData = () => {
  dispatch(fetchCount(5)).then((response) => {
    console.log(response);
  });
};

return (
  // ... Previous code omitted ...
  <button onClick={handleFetchData}>Fetch Data</button>
);

Using mapStateToProps to Retrieve Data

Understanding the Redux Store

Before diving into mapStateToProps, ensure you understand Redux basics. Redux is a state management library that maintains a single global state tree stored in the store. The store provides:

  • getState(): Retrieves the current state.
  • dispatch(action): Dispatches an action, which describes what happened.
  • subscribe(listener): Subscribes to state changes, calling the listener when the state changes.

Creating a Redux Store

Create a Redux store in your project. For a simple counter application, the store might look like this:

store.js

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

const store = createStore(rootReducer);

export default store;

Creating a Reducer

Create a reducer to handle state updates. A reducer is a pure function that takes the current state and an action, returning a new state.

counterReducer.js

const initialState = {
  count: 0
};

const counterReducer = (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;
  }
};

export default counterReducer;

Combining Reducers

In large applications, you may have multiple reducers managing different state parts. Use combineReducers to combine them.

index.js

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

const rootReducer = combineReducers({
  counter: counterReducer
});

export default rootReducer;

Using connect and mapStateToProps

Use the connect function to integrate mapStateToProps into a React component.

App.js

import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from './actions';

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Counter: {this.props.count}</h1>
        <button onClick={() => this.props.increment()}>+</button>
        <button onClick={() => this.props.decrement()}>-</button>
      </div>
    );
  }
}

// mapStateToProps function
const mapStateToProps = (state) => {
  return {
    count: state.counter.count
  };
};

// Connect component to store
export default connect(mapStateToProps, { increment, decrement })(App);

Deep Dive into mapStateToProps

mapStateToProps takes a state parameter, which is the global state from the Redux store, and returns an object whose keys become the component’s props. In the example, state.counter.count is mapped to props.count.

Optimizing mapStateToProps

In large applications, mapStateToProps can become complex. Use the reselect library to improve performance and readability by creating selector functions that recompute only when necessary.

Using reselect

import { createSelector } from 'reselect';

// Create a selector
const selectCounter = createSelector(
  (state) => state.counter,
  (counter) => counter.count
);

// Use selector in mapStateToProps
const mapStateToProps = (state) => ({
  count: selectCounter(state)
});

Best Practices for mapStateToProps

  • Keep Functions Pure: mapStateToProps should be a pure function, avoiding state modifications or side effects.
  • Avoid Unnecessary Re-renders: Use reselect or memoization to cache results, preventing recomputation on every store update.
  • Separate Business Logic: Place complex logic in selectors or helper functions to keep mapStateToProps clean.
  • Clear Naming: Use clear, descriptive prop names to avoid ambiguity.

Using mapDispatchToProps to Dispatch Actions

In React and Redux integrated applications, mapDispatchToProps is a function provided by the react-redux library to bind Redux’s dispatch method to a component’s props, enabling the component to trigger Redux actions directly.

Defining Actions

Define your actions, which are plain JavaScript objects with at least a type property indicating the action type. You can also define action creator functions that return action objects.

actions.js

export const increment = () => {
  return {
    type: 'INCREMENT'
  };
};

export const decrement = () => {
  return {
    type: 'DECREMENT'
  };
};

Creating a Reducer

Create a reducer to handle these actions. The reducer is a pure function that determines the new state based on the current state and action.

counterReducer.js

const initialState = {
  count: 0
};

const counterReducer = (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;
  }
};

export default counterReducer;

Creating a Store

Use createStore and applyMiddleware (if middleware is needed) to create the Redux store.

store.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;

Using mapDispatchToProps

Bind actions to a component using mapDispatchToProps. It can accept two parameters: a function returning an object where keys are prop names and values are action creators, or the component’s props.

App.js

import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from './actions';

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Counter: {this.props.count}</h1>
        <button onClick={this.props.increment}>+</button>
        <button onClick={this.props.decrement}>-</button>
      </div>
    );
  }
}

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

// Using mapDispatchToProps
const mapDispatchToProps = {
  increment,
  decrement
};

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

Alternatively, use the function form:

const mapDispatchToProps = (dispatch) => {
  return {
    increment: () => dispatch(increment()),
    decrement: () => dispatch(decrement())
  };
};

Dispatching Actions via Props

In the component, dispatch actions using this.props.increment and this.props.decrement.

Creating and Accessing the Store

Creating a Redux Store

The Redux store is the single source of truth for all application state, containing the entire state tree.

Creating the store

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

const store = createStore(rootReducer);

export default store;

Configuring Redux DevTools

For easier debugging, use the Redux DevTools middleware. Install the redux-devtools-extension package.

npm install redux-devtools-extension

Add DevTools middleware when creating the store.

Store with DevTools

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;

Using Provider to Wrap the Application

Use the Provider component from react-redux to pass the store to all child components.

Using Provider in the root component

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

Accessing Store State

In React components, use the useSelector hook to access store state. useSelector returns the state based on the selector function provided.

Using useSelector

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

function Counter() {
  const count = useSelector(state => state.counter.value);

  return (
    <div>
      <p>You clicked {count} times</p>
    </div>
  );
}

Manipulating Store State

To modify store state, use the useDispatch hook to dispatch actions. useDispatch returns the store’s dispatch method.

Using useDispatch

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { increment, decrement } from './actions';

function Counter() {
  const dispatch = useDispatch();
  const [value, setValue] = useState(0);

  const handleClick = () => {
    if (value > 0) {
      dispatch(decrement(value));
    } else {
      dispatch(increment(-value));
    }
    setValue(0);
  };

  return (
    <div>
      <input type="number" value={value} onChange={e => setValue(Number(e.target.value))} />
      <button onClick={handleClick}>Submit</button>
    </div>
  );
}

Creating and Using Actions

Actions are plain JavaScript objects describing state changes. Create action creator functions to generate actions.

Creating actions

export const increment = amount => {
  return {
    type: 'INCREMENT',
    payload: amount
  };
};

export const decrement = amount => {
  return {
    type: 'DECREMENT',
    payload: amount
  };
};

Creating Reducers

Reducers are pure functions that determine the new state based on the current state and action. Each reducer handles a part of the application’s state tree.

Creating a reducer

const initialState = {
  value: 0
};

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, value: state.value + action.payload };
    case 'DECREMENT':
      return { ...state, value: state.value - action.payload };
    default:
      return state;
  }
};

export default counterReducer;

Combining Reducers

In large applications, use combineReducers to combine multiple reducers managing different state parts.

Combining reducers

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

const rootReducer = combineReducers({
  counter: counterReducer
});

export default rootReducer;

Using Thunk Middleware for Async Actions

Reducers cannot handle asynchronous operations directly. Use the Thunk middleware to manage async actions.

Creating a Thunk action creator

import axios from 'axios';

export const fetchUsers = () => async dispatch => {
  try {
    const response = await axios.get('https://api.example.com/users');
    dispatch({ type: 'FETCH_USERS_SUCCESS', payload: response.data });
  } catch (error) {
    dispatch({ type: 'FETCH_USERS_FAILURE', payload: error.message });
  }
};

Handling Async Actions in Reducers

Handle actions generated by Thunk action creators in the reducer.

Handling async actions

const initialState = {
  users: [],
  loading: false,
  error: null
};

const userReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_USERS_SUCCESS':
      return { ...state, users: action.payload, loading: false, error: null };
    case 'FETCH_USERS_FAILURE':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};

React Redux Core APIs

Provider

The Provider component in React Redux passes the Redux store reference to its child component tree using React’s Context API, allowing any child component to access the store without explicitly passing props.

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

useSelector and useDispatch

Since React Redux 7.1, the useSelector and useDispatch hooks provide an alternative to connect, making components cleaner, easier to understand, and maintainable.

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import * as actions from './actions';

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

  const increment = () => dispatch(actions.increment());
  const decrement = () => dispatch(actions.decrement());

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
};

export default Counter;

connect()

The connect higher-order component (HOC) maps a portion of the Redux store state to a React component’s props and can also map action dispatchers to props.

import React from 'react';
import { connect } from 'react-redux';
import * as actions from './actions';

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

const mapDispatchToProps = dispatch => ({
  increment: () => dispatch(actions.increment()),
  decrement: () => dispatch(actions.decrement())
});

const Counter = ({ count, increment, decrement }) => (
  <div>
    <h1>{count}</h1>
    <button onClick={increment}>+</button>
    <button onClick={decrement}>-</button>
  </div>
);

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

batch()

Introduced in React Redux 8, the batch method allows multiple actions to be executed in a single update cycle, avoiding unnecessary re-renders and improving performance.

import { configureStore } from '@reduxjs/toolkit';
import { batch } from 'react-redux';

const store = configureStore({
  reducer: {
    // ...
  },
});

store.dispatch(batch(() => {
  store.dispatch(actions.increment());
  store.dispatch(actions.decrement());
}));

Share your love