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.
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.
REDUX store file
An example of a counter management system with React-Redux.
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.
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.
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.
Top comments (0)