DEV Community

Khayrul
Khayrul

Posted on

React context API

Context API is a new addition of React JS. It's an awesome feature is react. Context API makes the state management system becomes more manageable. Before coming context API, we passed state from one component to another component using props and the way was harder because, in a large application, it will be uncontrollable. Here context API helps us a lot and It is the best way to ignore props drilling. In the context API part, we will learn different purposes of context API and how to create a context, and how to use it.

Uses of context API and a simple example:
We can create a context API in four steps,

  1. First, we have to create a context using createContext method
  2. Then we have to wrap all necessary components using Context.Provider where we want to pass the context value.
  3. Then pass the value using value props inside Context.Provider.
  4. Then we can read or use the provided value using Context.Consumer or using useConetxt hook. Example:
import React, { createContext, useContext } from 'react';
export const MyContext = createContext();
function App() {
  const name = "Khayrul"
  return (
    <MyContext.Provider value={name}>
      <Author />
    </MyContext.Provider>
  )
}
const Author = () => {
  const value = useContext(MyContext);
  return <h1>{value}</h1>;
}
export default App;
Enter fullscreen mode Exit fullscreen mode

React Context API vs Redux:
Many people think that, is context PAI replace Redux. The answer is No. Because some of the case context API is helpful and some of the case Redux is not ignorable.

Redux is a complete state management library. Redux is an efficient way to manage the state and in some cases, it is mandatory to use. In a large application, we may have so many states, and managing those states using context API or props drilling is very difficult. Here we should use Redux.
On the other hand, in a small application, using redux is not preferable, and it's one kind of harmful. Because for a simple action we have to write code in three or more files. Here we use context API or props drilling system.

Top comments (0)