Intro
Tutorial about authorization handling in React. We'll write it in a generic and easy-to-use way! You will be able to use it in every React app.
Prelude
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.
Loading
2. Provider
We create a provider that will hold information via the Context API. In useEffect we're calling backend for status.
Loading
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.
Loading
4. Usage
It's time for a use case example. We are going to use the default layout rendered with create-react-app.
Loading
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 😉.
Summary
In summary, this short article shows how authorization logic can be implemented with context API and some design patterns commonly used in React.
Comments
Add your honest opinion about this article and help us improve the content.