Authorization made simple
4m
Intro
Short and simple article on the topic of authorization in React, so as not to get hung up on it.
Authorization
is one of the more common functionalities when it comes to web applications. Checking whether a user is logged in or not can generate a lot of code. Let's write some utils, that will make it easy.1. Service
To fully illustrate the problem, we will use the prepared login mock API call. The following function waits 3 seconds and then simulates a BE query that returns a flag.
2. Provider
We create a
provider
that will hold information via the Context API
. In useEffect
we're calling backend for status.3. Guards
Our custom hook will be used to implement
reusable
logic. We will now write two guards that depending on the values stored in the provider will render (or not) part of the UI.4. Usage
It's time for a use case example. We are going to use the default layout rendered with
create-react-app
.As you can see, from now on hiding or showing parts of the layout is trivial 🤡. Of course, let's not forget that we need to use our provider in the parent component 😉.
In summary, this short article shows how authorization logic can be implemented with context API and some design patterns commonly used in React.
created: 2 months ago
updated: 2 months ago