?????? ????? ??????????3
?????? ????? ??????????3
Global State
Management
In React (Part 3)
@oluwakemi Oluwadahunsi
The “All-mighty” Redux
@oluwakemi Oluwadahunsi
Redux enables centralized state management,
where all state is managed in one place (the store),
and changes to state follow a unidirectional data
flow pattern, making your application more
predictable and easier to debug.
@oluwakemi Oluwadahunsi
How Redux Works:
@oluwakemi Oluwadahunsi
Setting Up Redux In React
To show the steps involved in managing global
state with Redux in a React project, let's walk
through setting up Redux and using it to fetch data
from an API.
@oluwakemi Oluwadahunsi
The Basic Method
Step 1: Setting Up Redux with React
To begin, let's install the required packages for
Redux and React integration.
@oluwakemi Oluwadahunsi
Step 2: Create a Redux Store
@oluwakemi Oluwadahunsi
fetchDataRequest: Indicates the start of the
data fetching process.
fetchDataSuccess: Fired when the data is
successfully fetched.
fetchDataFailure: Fired if there's an error
fetching data.
@oluwakemi Oluwadahunsi
initial state of the reducers
@oluwakemi Oluwadahunsi
In the file above:
@oluwakemi Oluwadahunsi
Step 5: Combine Reducers (if multiple reducers)
@oluwakemi Oluwadahunsi
Step 6: Connecting Redux to React
Provider wrapping
around the entire app
@oluwakemi Oluwadahunsi
This fetchData function uses thunk middleware to
handle asynchronous logic. To use this, install
redux-thunk
@oluwakemi Oluwadahunsi
Step 8: Create React Component to Display
Fetched Data
Create a component named “UserList.jsx/jsx” in
your “components” folder”
@oluwakemi Oluwadahunsi
useDispatch: Dispatches the fetchData action
when the component mounts.
@oluwakemi Oluwadahunsi
Setup Using Redux Toolkit
Redux Toolkit (RTK) is the official, recommended
way to write Redux logic. One of its key features is
slices, which help to streamline the process of
writing reducers, actions, and handling side
effects.
@oluwakemi Oluwadahunsi
Step 1: Setting Up Redux Toolkit
@oluwakemi Oluwadahunsi
initial state defined
reducers used
for updating
the states
@oluwakemi Oluwadahunsi
In the userSlice.js file:
@oluwakemi Oluwadahunsi
Instead of using the deprecated createStore
method in the old setup, we use Redux Toolkit's
configureStore, and you don’t need to worry about
adding middleware like thunk, it’s included by
default.
@oluwakemi Oluwadahunsi
Now run your application to view the fteched data
in your browser. You should see a list of user’s data
displayed.
@oluwakemi Oluwadahunsi
I hope you found this material
useful and helpful.
Remember to:
Like
&
Share with your network, be
helpful to someone 👌
@oluwakemi Oluwadahunsi
Hi There!
Thank you for reading through
Did you enjoy this knowledge?
kodemaven-portfolio.vercel.app