๐Manage Auth State
Using redux to manage auth state across the React app.
We can use Redux
or React Context
to set up a global / app-wide state. Since the authentication state is not in any way going to affect app performance, we can use React Context here. But I prefer using Redux here.
Redux for Auth State
We will use the @reduxjs/toolkit
to manage our app wide state. So first we need to install all the dependencies.
Installing dependencies
Creating the authSlice
authSlice
Now, we create the authSlice
to create our reducers, provider default actions and manage state in our Redux store.
Connect Reducers to Store
Now, we need to attach this reducer to the central Redux store
.
Provide Store to App
Now after creating the store
and connecting the reducers
to it, we need to provide
the store as an app-wide state
.
Using Actions to Login
Now we have all the things in place, it is time to use the Redux store actions provided by the authSlice
slice.
Verifying Login Success
After successful sign-up, we can check if the login is successful or not using the Redux DevTool
in the browser. It gives us the app-wide auth state, which contains the current logged-in user's authentication token
as well as the state specifying if the use has logged in, which is a boolean value [isLoggedIn
].
After a successful login, we can see the following changes in the Redux DevTool:
Last updated