React Auth with High Order Component
In this article, I will try to answer the questions of what is High Order Component (HOC) and how can I use it with Auth.
When I tried to do auth with React, I went through various searches and met HOC. What is this HOC ? As the name suggests, you can think of it as a high priority component. It can basically take a function and return a function. The goal is to add additional functionality to our functions.
So why should I use HOC ? Sometimes we want to define a common behavior for some components, such as the user control that I will talk about in this article. It becomes much more advantageous to create a structure that can be managed from a single place instead of querying it one by one in all components. Moreover, it has a very simple structure.
With the example below, you will see that it has a simple structure.
As in the example, there is a function in our component and we return it. What we return in the function is entirely up to us, but in this example, I set up a context and userAuth structure. So here I will check the existence of user very simply. Now let’s take a look at how the context structure is.
We set up a basic context structure above. To explain a little bit, we will basically try to do our operations with user, loading and login. In order to see all the steps, we wait 3 seconds in the login function and do the operations that way. We would like to see a loading screen during this time. And finally, we check the loading status and take action accordingly and send our values in the provider.
After finishing our work on the context side, it remains to integrate it on the HOC side. We are making some changes on the first HOC code we wrote. We include the user state from the context structure we created. Then we check the existing user and take action accordingly. In my example, if the user is not specific, it is redirected to the Login page so that he can login. If there is a certain user, it is directed to our component that we receive as props in Auth.
Finally, in cases where the user is undefined, we wrap components which we want to protect with the HOC we created.
As an example, I created a dashboard component and I don’t want it to be accessed before the login process takes place. I can protect it in the following way.
That’s it ! You can access all these codes from the relevant link in my github profile. Here!