Getting Started With Redux: Learn by Example
In this second post of the series, we are going to bolster our understanding of Redux and build on top of what we already know. We will start by creating a realistic Redux application—a contact list—that's more complex than a basic counter. This will help you strengthen your understanding of the single store and multiple reducers concept which I introduced in the previous tutorial. Then later we'll talk about binding your Redux state with a React application and the best practices that you should consider while creating a project from scratch.
However, it's okay if you haven't read the first post—you should still be able to follow along as long as you know the Redux basics. The code for the tutorial is available in the repo, and you can use that as a starting point.
Creating a Contact List Using Redux
We're going to build a basic contact list with the following features:
- display all contacts
- search for contacts
- fetch all contacts from the server
- add a new contact
- push the new contact data into the server
Here's what our application is going to look like:


Covering everything in one stretch is hard. So in this post we're going to focus on just the Redux part of adding a new contact and displaying the newly added contact. From a Redux perspective, we'll be initializing the state, creating the store, adding reducers and actions, etc.
In the next tutorial, we'll learn how to connect React and Redux and dispatch Redux actions from a React front-end. In the final part, we'll shift our focus towards making API calls using Redux. This includes fetching the contacts from the server and making a server request while adding new contacts. Apart from that, we'll also create a search bar feature that lets you search all the existing contacts.
Create a Sketch of the State Tree
You can download the react-redux demo application from my GitHub repository. Clone the repo and use the v1 branch as a starting point. The v1 branch is very similar to the create-react-app template. The only difference is that I've added a few empty directories to organise Redux. Here's the directory structure.
.<br>├── package.json<br>├── public<br>├── README.md<br>├── src<br>│ ├── actions<br>│ ├── App.js<br>│ ├── components<br>│ ├── containers<br>│ ├── index.js<br>│ ├── reducers<br>│ └── store<br>└── yarn.lock<br>
Alternatively, you can create a new project from scratch. Either way, you will need to have installed a basic react boilerplate and redux before you can get started.
It's a good idea to have a rough sketch of the state tree first. In my opinion, this will save you lots of time in the long run. Here's a rough sketch of the possible state tree.
const initialState = {<br> contacts: {<br> contactList: [],<br> newContact: {<br> name: '',<br> surname: '',<br> email: '',<br> address: '',<br> phone: ''<br> },<br> ui: {<br> //All the UI related state here. eg: hide/show modals,<br> //toggle checkbox etc.<br> }<br> }<br>}<br> <br>
Our store needs to have two properties—combineReducers that lets you create multiple reducers and then combine them into a single reducing function. The combineReducers function enhances readability. So I am going to split the reducer into two—a useState hook to manage component-level state within your React application.
In that same spirit, Redux has introduced some different hooks to enable us perform the usual tasks (dispatching an action, getting state, and so on) inside a functional component while writing minimal code. These hooks were first added in React Redux 7.1. For example, to dispatch actions and get the state tree, Redux provides the following hooks:
- useSelector: get the state tree or even a branch of the stat
Now, with these hooks, we can refactor the code above to this instead:
// Other imports here<br><br>// Import the redux hooks<br>import { useDispatch, useSelector } from 'react-redux'<br><br>// Return the dispatch function from hook<br>const dispatch = useDispatch()<br> <br>// Call getStore() to create store object<br>const store = getStore();<br><br>// Get state tree using useSelector<br>const state = useSelector(state => state)<br><br>// Gets the UI branch of the state<br>const ui = useSelector(state => state.UI)<br><br>/* returns isContactFormHidden returns false */<br>dispatch(toggleContactForm());<br>/* returns isContactFormHidden returns false */<br>dispatch(toggleContactForm());<br>/* updates the state of contacts.newContact object */<br>dispatch(handleInputChange('email', 'manjunath@example.com'))<br><br>unsubscribe();<br>
If everything is working right, you should see this in the developer console.

That's it! In the developer console, you can see the Redux store being logged, so you can see how it changes after each action.
Summary
We've created a bare-bones Redux application for our awesome contact list application. We learned about reducers, splitting reducers to make our app structure cleaner, and writing actions for mutating the store.
Towards the end of the post, we subscribed to the store using the store.subscribe()
method. Technically, this isn't the best way to get things done if you're going to use React with Redux. There are more optimized ways to connect the react front-end with Redux. We'll cover those in the next tutorial.
The above is the detailed content of Getting Started With Redux: Learn by Example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
