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.
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.
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.
We create a provider that will hold information via the Context API. In useEffect we're calling backend for status.
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.
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.