DEV Community

Cover image for React Context API
ekholil
ekholil

Posted on

React Context API

What is context api?

Reactjs is a powerful library for making user interface easily. It is the most popular JS library in this moment. When we make an application we have to work with many states or data. Context api allows us to pass down and use data or state whatever component we need in our react app without props. In other words, react context api allows us to share data across our components easily. React Context api provide us to manage complex state, nested state in a simpler and more effective way than using props.

Why use react context api?

A real world react application is going to need to share data or state between different components at different levels of react js hierarchy. They also need to share functions to execute different actions based on user interaction.

There are three main ways to achieve this :
Props: store state directly in the common ancestor component and pass it down as many components it needed, as props, until it reaches it target components. This is the easiest and simple way to share state or data between components. But the problem is when target component is very deep or very many then it is become so complex to pass down state through props. So it is not the proper war to share state in big or deep components.
Library: We can use a state management library such as Redux or Mobx. But this library comes with complexity and an extra learning curve that would not be suitable for some projects. This might be a good thing depending on project requirements. But the role is always to try to do the simplest thing first.
Context API: React context api store the state in a common ancestor component(Provider component) and access it from as many components as needed. Which can be nested at any depth under this ancestor. This is almost same as the props solution but difference is here any component can access the state in any context without props drilling.

How to use React Context API :

There are four steps to use context api in a react application.
Create context using createContext() method.
Wrap the ancestor component with created context using provider.
Put any value or state you like to share on context provider using value props.
Read this value from any component using context consumer

Conclusion
React context api makes our life easy. Now with the help of context api we can easily make react application.

Top comments (0)