Random UTF-8 characters

Home

22 Jun 2016 in reactjavascript

React: Context

React context is one of those features I discovered later that I should have. It's perfect place to hold your apps user context object. In this post I'll outline how to place a user object into the context and access it from any component in your app.

The app context is like a global variable. While global variables are often misused, they do have some useful applications. Like most apps we need to hold on to the user who is currently logged in. We do this by placing this user into the app context.

Now this user object can be used by any component in the app. If we wanted to render a user edit form, we can pull the user from the context.

You can also access the app context from stateless functional components. Here is the same control written as a function.

The main draw back of using context is that data flow becomes harder to follow. The alternative would be to use props to pass this data, this would be a more explicit method. Don't overuse context, there are only a few use cases where its application is correct!

Happy coding!