DEV Community

Hello Dev World Blog
Hello Dev World Blog

Posted on • Updated on • Originally published at hellodevworld.com

When to Use a React Context vs a JS file

Everyone loves react contexts. A little too much in my opinion… You go into a new React project now and its like

Lets take a step back and talk about what a context is, when you should use one, and when you should just go with a simple JavaScript file instead.

TLDR: If you need to share data (more than a couple of props) between multiple levels of components (ex: grandparent to grandchild or deeper) or if multiple sections of the application need access to certain data use a context. Otherwise you can just use a normal JavaScript file to keep your data and presentation separate.

What is a Context

All a context is is a way to pass data through components without having to prop drill (pass props down to each component). This is great because rather than having to have your data pass through 4 components and remember to add it to each component we can just access the data we need at each level

When to Use a Context

Since its release a lot of people have been using contexts everywhere. Anywhere they are retrieving or manipulating data they are using a context instead of just a normal JavaScript file. Contexts are great but they are also a good amount of overhead and not always necessary. If you are not passing data more than one level or using data globally you do not need a context. Just use a normal JavaScript file. Now I know some of you are saying “but what if we need that data later why not just make it a context now?” and the answer is because you don’t need to. Making something a context later is very easy to do and can be done if you need it but not every parent component needs a context. not every grandparent does either. Not all grandparent components share data with the children.

Popular Use Cases for Contexts

  • User access information (authentication)

  • Theming

  • Grandparent to grandchild data sharing

  • Global State Management

Top comments (0)