Welcome to our comprehensive guide on Redux Flow! In this tutorial, we'll learn how to manage state effectively in React JS applications, using Redux - a popular library for managing state in JavaScript. Let's dive in!
Redux is a predictable state container for JavaScript applications. It helps us manage the state of our application by centralizing it in a single store. This makes our application predictable, easier to test, and maintain.
To set up Redux in your React JS project, you'll need to install a few packages:
npm install redux react-reduxActions: Dispatch an action to change the state of the application.
Action Creators: Functions that return an action.
Reducers: Functions that handle actions and return a new state based on the current state and action.
Store: Centralized place where the state of the application is stored.
React-Redux: Connects your React components to the Redux store.
// Action Types
const ADD_TODO = 'ADD_TODO';
const DELETE_TODO = 'DELETE_TODO';
// Action Creator for adding a todo
function addTodo(text) {
return {
type: ADD_TODO,
payload: {
id: Date.now(),
text
}
};
}
// Action Creator for deleting a todo
function deleteTodo(id) {
return {
type: DELETE_TODO,
payload: id
};
}// Initial State
const initialState = {
todos: []
};
// Root Reducer
function todoApp(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload]
};
case DELETE_TODO:
return {
...state,
todos: state.todos.filter(todo => todo.id !== action.payload)
};
default:
return state;
}
}import { createStore } from 'redux';
import todoApp from './reducers';
const store = createStore(todoApp);import React from 'react';
import { connect } from 'react-redux';
import { addTodo, deleteTodo } from './actions';
// Your Component
function TodoList(props) {
return (
<ul>
{props.todos.map(todo => (
<li key={todo.id}>
{todo.text}
<button onClick={() => props.deleteTodo(todo.id)}>Delete</button>
</li>
))}
<button onClick={props.addTodo}>Add Todo</button>
</ul>
);
}
// Map State to Props
const mapStateToProps = state => ({
todos: state.todos
});
// Map Dispatch to Props
const mapDispatchToProps = {
addTodo,
deleteTodo
};
// Connected Component
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);What does Redux help us manage in a React JS application?
That's it for today's tutorial! In the next lesson, we'll learn how to use Middleware in Redux to handle asynchronous actions. Until then, happy coding! 🚀🚀