React Advanced

0% completed

Previous
Next
Connecting Redux to your React Application

Connecting Redux to a React application involves integrating the Redux store with your React components so that your components can access and update the global state managed by Redux.

Redux is primarily designed for managing the state of large applications, while React focuses on building UI components. By combining both, you can manage the state centrally using Redux and let React handle the rendering of the UI.

To connect Redux to a React app, you need to follow these key steps:

  1. Install Redux and React-Redux.
  2. Create a Redux store.
  3. Provide the store to your React app.
  4. Connect your React components to the Redux store using useDispatch() and useSelector() hooks.

Let’s break down each step in detail, continuing with our simple to-do app example.

1. Create a Redux Store

In Redux, the store holds the application state and provides methods to interact with it. We’ve already seen how to create a store earlier.

Here’s a simple store setup for the to-do app example:

// reducers.js const initialState = []; const todosReducer = (state = initialState, action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, { id: Date.now(), text: action.payload.text, completed: action.payload.completed }; case 'REMOVE_TODO': return state.filter(todo => todo.id !== action.payload.id); case 'TOGGLE_TODO': return state.map(todo => todo.id === action.payload.id ? { ...todo, completed: !todo.completed } : todo ); default: return state; } }; export default todosReducer;

Now, let’s create a Redux store that uses this reducer:

// store.js import { createStore } from 'redux'; import todosReducer from './reducers'; const store = createStore(todosReducer); export default store;

2. Provide the Store to Your React App

To allow your entire application to access the Redux store, you need to "provide" the store to your React app using the <Provider> component from the react-redux library.

Wrap your entire app with the <Provider> component in the root index.js or App.js file. The <Provider> component takes the Redux store as a prop and passes it down to all React components.

Here’s how you set up the provider:

// index.js or App.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; // Import the Provider component import store from './store'; // Import the store import App from './App'; // Import the main App component ReactDOM.render( <Provider store={store}> {/* Wrap the app with Provider */} <App /> </Provider>, document.getElementById('root') );

By wrapping your app in the <Provider>, all components inside your app will be able to access the Redux store.

3. Connecting React Components to Redux

React-Redux provides two hooks for interacting with the Redux store: useSelector() and useDispatch().

  • useSelector(): Allows your components to access values from the Redux store. It’s similar to mapStateToProps in class components.
  • useDispatch(): Provides a way to dispatch actions to the Redux store. It’s similar to mapDispatchToProps in class components.
Example

To connecting a functional component to Redux, let’s create a component that displays the list of to-dos and provides functionality to add a new to-do, toggle completion, and remove to-dos.

// TodoApp.js import React, { useState } from 'react'; import { useSelector, useDispatch } from 'react-redux'; // Import hooks from react-redux import { addTodo, toggleTodo, removeTodo } from './actions'; // Import actions const TodoApp = () => { const [text, setText] = useState(''); // Local state for input const todos = useSelector(state => state); // Access to the Redux store using useSelector const dispatch = useDispatch(); // Access to dispatch function using useDispatch // Handler to add a new to-do const handleAddTodo = () => { if (text) { dispatch(addTodo(text)); // Dispatch the addTodo action to the Redux store setText(''); // Reset the input field } }; return ( <div> <h1>Todo App</h1> <input type="text" value={text} onChange={(e) => setText(e.target.value)} // Update local state on input change placeholder="Enter a new to-do" /> <button onClick={handleAddTodo}>Add Todo</button> <ul> {todos.map((todo) => ( <li key={todo.id}> <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }} onClick={() => dispatch(toggleTodo(todo.id))} // Dispatch toggleTodo on click > {todo.text} </span> <button onClick={() => dispatch(removeTodo(todo.id))}>Remove</button> </li> ))} </ul> </div> ); }; export default TodoApp;

Explanation:

  • useSelector(state => state): This hook is used to access the current state of the store. It gives us the list of to-dos.
  • useDispatch(): This hook is used to access the dispatch function, which is used to dispatch actions (like adding, toggling, or removing a to-do).

In this component:

  • The handleAddTodo function dispatches an action to add a new to-do to the store.
  • The onClick handler for the to-do item dispatches an action to toggle the completion status.
  • The onClick handler for the remove button dispatches an action to remove a to-do.

By following these steps, you can easily connect Redux with your React application to manage state efficiently and predictably.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next