DEV Community

Cover image for React Redux tutorial for beginners
Ankit Shrivastava
Ankit Shrivastava

Posted on • Edited on

React Redux tutorial for beginners

What is REDUX?

Redux is a state management system which is used with many programming languages. In React, Redux is used as a replacement for CONTEXT API.

The core principles of REDUX...

0. Single Source of truth:
Global state of the application is stored in a single place.

1. State is read-only:
The only way to change the state is by emitting actions.

2. Changes are made with pure functions:
The pure functions are known as REDUCERS which take two
arguments, one is previous state and the second is an action.
Previous state is evaluated with the passed action and a new
state is returned.

Creating store for React-Redux

 createStore() function is used to create a store which is 
 imported from redux library and this function accepts a 
 reducer function.
Enter fullscreen mode Exit fullscreen mode

Image description

Creating a reducer function

A reducer function is a normal function which accepts two 
arguments, a previous state and an action payload. Based on 
the evaluation of these two arguments, the reducer function
returns a new state.
Enter fullscreen mode Exit fullscreen mode

Image description

REDUX store file

An example of a counter management system with React-Redux.

Image description

Providing REDUX store to the root component

Provider component imported from "react-redux" library is used
to provide the REDUX store to the root component. The Provider 
component acts as a wrapper component and wraps the root 
component of the application. The Provider component has a 
"store" attribute to accept the REDUX store which establishes
the connection between Provider and REDUX store.

The child components of the root component are also exposed to
the REDUX store when the Provider component wraps it.
Enter fullscreen mode Exit fullscreen mode

Image description

Accessing state data from REDUX store

useSelector() hook imported from "react-redux" library is used
to tap into the REDUX store to access state data.
useSelector() does strict === reference equality checks.
useSelector() can be called multiple times within a single 
function component.
Enter fullscreen mode Exit fullscreen mode

Image description

Dispatching an action to the REDUX store

useDispatch() hook imported from "react-redux" library is used 
to dispatch actions to the REDUX store.
Behind the scenes when an action is dispatched, useSelector()
does a reference comparison of the previous selector result
value and current result value. If they are different, the 
component is forced to re-render.
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)