Jan 17, 2022Last modified May 17, 2025

Notes on react context API

More often than not, developers end up sharing the parent components state with child components by passing them through props.

This is often referred as "prop drilling".

The problem with prop drilling is that - you end up repeating the props for all the components between the parent and the child component. This leads to performance issues as a lot of these components gets rendered unnecesarily.

Components become polluted by props which they are not even using ( except for just passing then through).

To optimize this state sharing ( and avoid prop drilling ), react introduced context api.

img credit

Note that all consumers of the context get re rendered whenever the context changes. This is applicable for components which are not even using the part of the changed context. For this reason, we should specilize the context for one aspect e.g preferences, auth, theme etc. Dont generalize them, otherwise it causes unnecesary rerenders.

Using Context API

  1. Create Context Define a context with createContext(defaultValue).
import { createContext } from 'react';
const ThemeContext = createContext(); // Default value optional
import { createContext } from 'react';
const ThemeContext = createContext(); // Default value optional
  1. Provider Component Wrap components with Context.Provider to supply data.
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
  1. Consume Context Use useContext(Context) or Context.Consumer to access data.
const { theme } = useContext(ThemeContext);
const { theme } = useContext(ThemeContext);