Redux is used to manage the state of a React app in a centralized place. “State” simply refers to data you need to render the user interface correctly.
I remember when I was learning redux for the first time for one of my project the docs I was referring to seems so overwhelming to me. The state file, actions, reducers, dispatch and all the complex stuff redux has. It has this unidirectional flow. I have tried it with typescript/ Angular at first, configuration was a bit confusing.
But when I learned how to use it, I realized how powerful it is and well structured it has various tools to work with. I was so impressed the way it handle the whole state for you, and you can tell exactly by debugging where the bugs are coming from. It has this cool extensions Redux Toolkit and DevTools which help you see the state tree how it is changing and updating your state.
Let’s see how it works —
1. A single, centralized state (i.e. a global JS object you could say) which is not directly accessible or mutable
2. Reducer functions that contain the logic to change and update the global state (by returning a new copy of the old state with all the required changes)
3. Actions that can be dispatched to trigger a reducer function to run
4. Subscriptions to get data out of the global state (e.g. to use it in React components)
Lets understand basics of Redux first.
- Actions — So actions are the objects which carries the data to update the redux store they are the only source of information for the Store. Below is an example of Action creators that dispatch an action:
type is usually in all caps with its words separated by underscores. For example,
2. Reducers — Reducers are the pure functions and they are responsible for how the application changes in response to an action made by an end-user. Below is an example of a Reducer with a switch case that would return the new state based on the action:
3. Store —Store is where the application’s state is housed, it wrapped everything together to make the application work. There is only one store in any Redux application:
In below example we are wrapping the store to our root level so that app can be connected to the global Redux store.
connect method sets up a subscription behind the scenes. That’s Redux and how you use it in a React app in a nutshell.
To access the state and dispatch within Redux, use useSelector() and useDispatch() hooks, which were introduced by React-Redux with version 7.1 after React introduced hooks.
— When you are working with big projects, has lot of dependent components and complex data flow structure, high-frequency state update redux works perfect.
Thank you for reading this, I hope you find it helpful.