Pierre Hedkvist

Software developer and maker.
Interested in React, Rails, collaborative editing.
Find me on @pierrehedkvist, send me an email.

React Context used in Authentication

Posted on 08/14/2019

Context in React creates a global state for a tree. It gives the ability to pass data from a parent component to child component without passing props between several layers in a tree.


Passing props from a parent component to child component via multiple components in-between is called prop drilling. Generally, this is an anti-pattern. In the following example, you can see that data is passed through several layers until its being used.



If you have this pattern occurring in many components in your project. Then it might be a good time to consider using context. That way you do not need to pass an object as a prop all the way down to where it is being used.


Context is particularly useful when dealing with authentication. In many components, knowing whether or not a user is authenticated is necessary. This will determine what a user can and can't do. Typically a user can't create a blog post or make comment unless it is authenticated. Using context any given component can ask the global state if the user is authenticated.


In the following example, a AuthContext is created at the top level, containing a name of the user, and a flag isAuthenticated. A function which toggles the authentication state is also provided. Notice how no prop is passed to the child, instead, it has access to the authentication state by consuming the AuthContext.



When a component is consuming a context, it will find the closest context provider in the tree and use that value in the consumer.


Context is useful when you are prop drilling on several layers in the tree. Typically prop drilling only two layers is fine, but usually, when dealing with authentication, you will need authentication values deeply nested in a tree.


    Powered By ConvertKit