Overview of React Redux with an example

Last updated on May 28 2022
Nitin Ajmera

Table of Contents

Overview of React Redux with an example

Redux is an open-source JavaScript library used to manage application state. React uses Redux for building the user interface. It was first introduced by Dan Abramov and Andrew Clark in 2015.
React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model. React Redux is conceptually simple. It subscribes to the Redux store, checks to see if the data which your component wants have changed, and re-renders your component.
Redux was inspired by Flux. Redux studied the Flux architecture and omitted unnecessary complexity.
• Redux does not have Dispatcher concept.
• Redux has an only Store whereas Flux has many Stores.
• The Action objects will be received and handled directly by Store.

Why use React Redux?

The main reason to use React Redux are:
• React Redux is the official UI bindings for react Application. It is kept up-to-date with any API changes to ensure that your React components behave as expected.
• It encourages good ‘React’ architecture.
• It implements many performance optimizations internally, which allows to components re-render only when it actually needs.

Redux Architecture

reactJs 22
reactJs

The components of Redux architecture are explained below.
STORE: A Store is a place where the entire state of your application lists. It manages the status of the application and has a dispatch(action) function. It is like a brain responsible for all moving parts in Redux.
ACTION: Action is sent or dispatched from the view which are payloads that can be read by Reducers. It is a pure object created to store the information of the user’s event. It includes information such as type of action, time of occurrence, location of occurrence, its coordinates, and which state it aims to change.
REDUCER: Reducer read the payloads from the actions and then updates the store via the state accordingly. It is a pure function to return a new state from the initial state.

Redux Installation

Requirements: React Redux requires React 16.8.3 or later version.
To use React Redux with React application, you need to install the below command.
$ npm install redux react-redux –save

React Redux Example

In this section, we will learn how to implements Redux in React application. Here, we provide a simple example to connect Redux and React.
Step-1 Create a new react project using create-react-app command. I choose the project name: “reactproject.” Now, install Redux and React-Redux.
Step-2 Create Files and Folders
In this step, we need to create folders and files for actions, reducers, components, and containers. After creating folders and files, our project looks like as below image.

reactJs 23
reactJs

Step-3 Actions
It uses ‘type’ property to inform about data that should be sent to the Store. In this folder, we will create two files: index.js and index.spec.js. Here, we have created an action creator that returns our action and sets an id for every created item.
Index.js

1. let nextTodoId = 0 
2. export const addTodo = text => ({ 
3. type: 'ADD_TODO', 
4. id: nextTodoId++, 
5. text 
6. }) 
7. 
8. export const setVisibilityFilter = filter => ({ 
9. type: 'SET_VISIBILITY_FILTER', 
10. filter 
11. }) 
12. 
13. export const toggleTodo = id => ({ 
14. type: 'TOGGLE_TODO', 
15. id 
16. }) 
17. 
18. export const VisibilityFilters = { 
19. SHOW_ALL: 'SHOW_ALL', 
20. SHOW_COMPLETED: 'SHOW_COMPLETED', 
21. SHOW_ACTIVE: 'SHOW_ACTIVE' 
22. }

Index.spec.js

1. import * as actions from './index' 
2. 
3. describe('todo actions', () => { 
4. it('addTodo should create ADD_TODO action', () => { 
5. expect(actions.addTodo('Use Redux')).toEqual({ 
6. type: 'ADD_TODO', 
7. id: 0, 
8. text: 'Use Redux' 
9. }) 
10. }) 
11. 
12. it('setVisibilityFilter should create SET_VISIBILITY_FILTER action', () => { 
13. expect(actions.setVisibilityFilter('active')).toEqual({ 
14. type: 'SET_VISIBILITY_FILTER', 
15. filter: 'active' 
16. }) 
17. }) 
18. 
19. it('toggleTodo should create TOGGLE_TODO action', () => { 
20. expect(actions.toggleTodo(1)).toEqual({ 
21. type: 'TOGGLE_TODO', 
22. id: 1 
23. }) 
24. }) 
25. })

Step-4 Reducers
As we know, Actions only trigger changes in the app, and the Reducers specify those changes. The Reducer is a function which takes two parameters ‘Action’ and ‘State’ to calculate and return an updated State. It read the payloads from the ‘Actions’ and then updates the ‘Store’ via the State accordingly.
In the given files, each Reducer managing its own part of the global State. The State parameter is different for every Reducer and corresponds to the part of the ‘State’ it manages. When the app becomes larger, we can split the Reducers into separate files and keep them completely independent and managing different data domains.
Here, we are using ‘combineReducers’ helper function to add any new Reducers we might use in the future.
index.js

1. import { combineReducers } from 'redux' 
2. import todos from './todos' 
3. import visibilityFilter from './visibilityFilter' 
4. 
5. export default combineReducers({ 
6. todos, 
7. visibilityFilter 
8. }) 
Todos.js
1. const todos = (state = [], action) => { 
2. switch (action.type) { 
3. case 'ADD_TODO': 
4. return [ 
5. ...state, 
6. { 
7. id: action.id, 
8. text: action.text, 
9. completed: false 
10. } 
11. ] 
12. case 'TOGGLE_TODO': 
13. return state.map(todo => 
14. (todo.id === action.id) 
15. ? {...todo, completed: !todo.completed} 
16. : todo 
17. ) 
18. default: 
19. return state 
20. } 
21. } 
22. export default todos

Todos.spec.js

1. import todos from './todos' 
2. 
3. describe('todos reducer', () => { 
4. it('should handle initial state', () => { 
5. expect( 
6. todos(undefined, {}) 
7. ).toEqual([]) 
8. }) 
9. 
10. it('should handle ADD_TODO', () => { 
11. expect( 
12. todos([], { 
13. type: 'ADD_TODO', 
14. text: 'Run the tests', 
15. id: 0 
16. }) 
17. ).toEqual([ 
18. { 
19. text: 'Run the tests', 
20. completed: false, 
21. id: 0 
22. } 
23. ]) 
24. 
25. expect( 
26. todos([ 
27. { 
28. text: 'Run the tests', 
29. completed: false, 
30. id: 0 
31. } 
32. ], { 
33. type: 'ADD_TODO', 
34. text: 'Use Redux', 
35. id: 1 
36. }) 
37. ).toEqual([ 
38. { 
39. text: 'Run the tests', 
40. completed: false, 
41. id: 0 
42. }, { 
43. text: 'Use Redux', 
44. completed: false, 
45. id: 1 
46. } 
47. ]) 
48. 
49. expect( 
50. todos([ 
51. { 
52. text: 'Run the tests', 
53. completed: false, 
54. id: 0 
55. }, { 
56. text: 'Use Redux', 
57. completed: false, 
58. id: 1 
59. } 
60. ], { 
61. type: 'ADD_TODO', 
62. text: 'Fix the tests', 
63. id: 2 
64. }) 
65. ).toEqual([ 
66. { 
67. text: 'Run the tests', 
68. completed: false, 
69. id: 0 
70. }, { 
71. text: 'Use Redux', 
72. completed: false, 
73. id: 1 
74. }, { 
75. text: 'Fix the tests', 
76. completed: false, 
77. id: 2 
78. } 
79. ]) 
80. }) 
81. 
82. it('should handle TOGGLE_TODO', () => { 
83. expect( 
84. todos([ 
85. { 
86. text: 'Run the tests', 
87. completed: false, 
88. id: 1 
89. }, { 
90. text: 'Use Redux', 
91. completed: false, 
92. id: 0 
93. } 
94. ], { 
95. type: 'TOGGLE_TODO', 
96. id: 1 
97. }) 
98. ).toEqual([ 
99. { 
100. text: 'Run the tests', 
101. completed: true, 
102. id: 1 
103. }, { 
104. text: 'Use Redux', 
105. completed: false, 
106. id: 0 
107. } 
108. ]) 
109. }) 
110. })

VisibilityFilter.js

1. import { VisibilityFilters } from '../actions' 
2. 
3. const visibilityFilter = (state = VisibilityFilters.SHOW_ALL, action) => { 
4. switch (action.type) { 
5. case 'SET_VISIBILITY_FILTER': 
6. return action.filter 
7. default: 
8. return state 
9. } 
10. } 
11. export default visibilityFilter

Step-5 Components
It is a Presentational Component, which concerned with how things look such as markup, styles. It receives data and invokes callbacks exclusively via props. It does not know where the data comes from or how to change it. It only renders what is given to them.
App.js
It is the root component which renders everything in the UI.

1. import React from 'react' 
2. import Footer from './Footer' 
3. import AddTodo from '../containers/AddTodo' 
4. import VisibleTodoList from '../containers/VisibleTodoList' 
5. 
6. const App = () => ( 
7. <div> 
8. <AddTodo /> 
9. <VisibleTodoList /> 
10. <Footer /> 
11. </div> 
12. ) 
13. export default App

Footer.js
It tells where the user changes currently visible todos.

1. import React from 'react' 
2. import FilterLink from '../containers/FilterLink' 
3. import { VisibilityFilters } from '../actions' 
4. 
5. const Footer = () => ( 
6. <p> 
7. Show: <FilterLink filter={VisibilityFilters.SHOW_ALL}>All</FilterLink> 
8. {', '} 
9. <FilterLink filter={VisibilityFilters.SHOW_ACTIVE}>Active</FilterLink> 
10. {', '} 
11. <FilterLink filter={VisibilityFilters.SHOW_COMPLETED}>Completed</FilterLink> 
12. </p> 
13. ) 
14. export default Footer 
Link.js
It is a link with a callback.
1. import React from 'react' 
2. import PropTypes from 'prop-types' 
3. 
4. const Link = ({ active, children, onClick }) => { 
5. if (active) { 
6. return <span>{children}</span> 
7. } 
8. 
9. return ( 
10. <a 
11. href="" 
12. onClick={e => { 
13. e.preventDefault() 
14. onClick() 
15. }} 
16. > 
17. {children} 
18. </a> 
19. ) 
20. } 
21. 
22. Link.propTypes = { 
23. active: PropTypes.bool.isRequired, 
24. children: PropTypes.node.isRequired, 
25. onClick: PropTypes.func.isRequired 
26. } 
27. 
28. export default Link 
Todo.js
It represents a single todo item which shows text.
1. import React from 'react' 
2. import PropTypes from 'prop-types' 
3. 
4. const Todo = ({ onClick, completed, text }) => ( 
5. <li 
6. onClick={onClick} 
7. style={{ 
8. textDecoration: completed ? 'line-through' : 'none' 
9. }} 
10. > 
11. {text} 
12. </li> 
13. ) 
14. 
15. Todo.propTypes = { 
16. onClick: PropTypes.func.isRequired, 
17. completed: PropTypes.bool.isRequired, 
18. text: PropTypes.string.isRequired 
19. } 
20. 
21. export default Todo 
TodoList.js
It is a list to show visible todos{ id, text, completed }.
1. import React from 'react' 
2. import PropTypes from 'prop-types' 
3. import Todo from './Todo' 
4. 
5. const TodoList = ({ todos, onTodoClick }) => ( 
6. <ul> 
7. {todos.map((todo, index) => ( 
8. <Todo key={index} {...todo} onClick={() => onTodoClick(index)} /> 
9. ))} 
10. </ul> 
11. ) 
12. 
13. TodoList.propTypes = { 
14. todos: PropTypes.arrayOf( 
15. PropTypes.shape({ 
16. id: PropTypes.number.isRequired, 
17. completed: PropTypes.bool.isRequired, 
18. text: PropTypes.string.isRequired 
19. }).isRequired 
20. ).isRequired, 
21. onTodoClick: PropTypes.func.isRequired 
22. } 
23. export default TodoList

Step-6 Containers
It is a Container Component which concerned with how things work such as data fetching, updates State. It provides data and behavior to presentational components or other container components. It uses Redux State to read data and dispatch Redux Action for updating data.
AddTodo.js
It contains the input field with an ADD (submit) button.

1. import React from 'react' 
2. import { connect } from 'react-redux' 
3. import { addTodo } from '../actions' 
4. 
5. const AddTodo = ({ dispatch }) => { 
6. let input 
7. 
8. return ( 
9. <div> 
10. <form onSubmit={e => { 
11. e.preventDefault() 
12. if (!input.value.trim()) { 
13. return 
14. } 
15. dispatch(addTodo(input.value)) 
16. input.value = '' 
17. }}> 
18. <input ref={node => input = node} /> 
19. <button type="submit"> 
20. Add Todo 
21. </button> 
22. </form> 
23. </div> 
24. ) 
25. } 
26. export default connect()(AddTodo) 
FilterLink.js
It represents the current visibility filter and renders a link.
1. import { connect } from 'react-redux' 
2. import { setVisibilityFilter } from '../actions' 
3. import Link from '../components/Link' 
4. 
5. const mapStateToProps = (state, ownProps) => ({ 
6. active: ownProps.filter === state.visibilityFilter 
7. }) 
8. 
9. const mapDispatchToProps = (dispatch, ownProps) => ({ 
10. onClick: () => dispatch(setVisibilityFilter(ownProps.filter)) 
11. }) 
12. 
13. export default connect( 
14. mapStateToProps, 
15. mapDispatchToProps 
16. )(Link) 
VisibleTodoList.js
It filters the todos and renders a TodoList.
1. import { connect } from 'react-redux' 
2. import { toggleTodo } from '../actions' 
3. import TodoList from '../components/TodoList' 
4. import { VisibilityFilters } from '../actions' 
5. 
6. const getVisibleTodos = (todos, filter) => { 
7. switch (filter) { 
8. case VisibilityFilters.SHOW_ALL: 
9. return todos 
10. case VisibilityFilters.SHOW_COMPLETED: 
11. return todos.filter(t => t.completed) 
12. case VisibilityFilters.SHOW_ACTIVE: 
13. return todos.filter(t => !t.completed) 
14. default: 
15. throw new Error('Unknown filter: ' + filter) 
16. } 
17. } 
18. 
19. const mapStateToProps = state => ({ 
20. todos: getVisibleTodos(state.todos, state.visibilityFilter) 
21. }) 
22. 
23. const mapDispatchToProps = dispatch => ({ 
24. toggleTodo: id => dispatch(toggleTodo(id)) 
25. }) 
26. 
27. export default connect( 
28. mapStateToProps, 
29. mapDispatchToProps 
30. )(TodoList)

Step-7 Store
All container components need access to the Redux Store to subscribe to it. For this, we need to pass it(store) as a prop to every container component. However, it gets tedious. So we recommend using special React Redux component called which make the store available to all container components without passing it explicitly. It used once when you render the root component.
index.js

1. import React from 'react' 
2. import { render } from 'react-dom' 
3. import { createStore } from 'redux' 
4. import { Provider } from 'react-redux' 
5. import App from './components/App' 
6. import rootReducer from './reducers' 
7. 
8. const store = createStore(rootReducer) 
9. 
10. render( 
11. <Provider store={store}> 
12. <App /> 
13. </Provider>, 
14. document.getElementById('root') 
15. )

Output
When we execute the application, it gives the output as below screen.

reactJs 24
reactJs

Now, we will be able to add items in the list.
The detailed explanation of React-Redux example can be shown here: https://redux.js.org/basics/usage-with-react.

So, this brings us to the end of blog. This Tecklearn ‘Overview of React Redux with an example’ blog helps you with commonly asked questions if you are looking out for a job in React JS and Front-End Development. If you wish to learn React JS and build a career in Front-End Development domain, then check out our interactive, React.js with Redux Training, that comes with 24*7 support to guide you throughout your learning period.

React.js with Redux Training

About the Course

Tecklearn’s React JS Training Course will help you master the fundamentals of React—an important web framework for developing user interfaces—including JSX, props, state, and events. In this course, you will learn how to build simple components & integrate them into more complex design components. After completing this training, you will be able to build the applications using React concepts such as JSX, Redux, Asynchronous Programming using Redux Saga middleware, Fetch data using GraphQL, perform Testing using Jest, successively Deploy applications using Nginx and Docker plus build Mobile applications using React Native. Accelerate your career as a React.js developer by enrolling into this React.js training.

Why Should you take React.js with Redux Training?

• The average salary for “React Developer” ranges from $100,816 per year to $110,711 per year, based on the role (Front End Developer/Full Stack Developer) – Indeed.com
• React Native Supports Cross-platform Development (iOS and Android), and it can reduce the development effort by almost 50% without compromising quality or productivity
• Currently, React JS is being used by major companies like Walmart, Netflix, and HelloSign.

What you will Learn in this Course?

Introduction to Web Development and React.js
• Fundamentals of React
• Building Blocks of Web Application Development
• Single-page and Multi-page Applications
• Different Client-side Technologies
• MVC Architecture
• Introduction to React
• Installation of React
• JSX and its use case
• DOM
• Virtual DOM and its working
• ECMAScript
• Difference between ES5 and ES6
• NPM Modules

Components, JSX & Props
• React Elements
• Render Function
• Components
• Class Component
• Thinking In Components
• What Is JSX
• JSX Expressions
• Creating Your First Component
• Functional Components

React State Management using Redux
• Need of Redux
• Redux Architecture
• Redux Action
• Redux Reducers
• Redux Store
• Principles of Redux
• Pros of Redux
• NPM Packages required to work with Redux
• More about react-redux package
React & Redux
• The React Redux Node Package
• Provider Component
• Connecting React Components with Redux Store
• Reducer Composition
• Normalization: Points to Keep in Mind When Designing a Redux Store
• Redux Middleware

React Hooks
• Caveat of JavaScript classes.
• Functional components and React hooks
• What are React hooks?
• Basic hooks
• useState() hook
• How to write useState() hook when state variable is an array of objects
• useEffect() hook
• Fetch API data using useEffect() hook
• useContext() hook
• Rules to write React hooks
• Additional hooks
• Custom hooks

Fetch Data using GraphQL
• What is GraphQL?
• Cons of Rest API
• Pros of GraphQL
• Frontend backend communication using GraphQL
• Type system
• GraphQL datatypes
• Modifiers
• Schemas
• GraphiQL tool
• Express framework
• NPM libraries to build server side of GraphQL
• Build a GraphQL API
• Apollo client
• NPM libraries to build client side of GraphQL
• How to setup Apollo client

React Application Testing and Deployment
• Define Jest
• Setup Testing environment
• Add Snapshot testing
• Integrate Test Reducers
• Create Test Components
• Push Application on Git
• Create Docker for React Application

Introduction to React Native
• What is React Native
• Use of JSX elements With React Native
• The anatomy of a React Native application
• React Native installation and setup
• Running the app on Android Simulator and Android Device
• Working with Styles and Layout
• Connecting React Native to Redux

React with Redux Projects

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Overview of React Redux with an example"

Leave a Message

Your email address will not be published. Required fields are marked *