React: Context API (Built-in) : code example

Why we're using Context API and when?

The main reason is to
Simplifying Prop Drilling & Sharing Global data

  • Passing props through many levels of components can become cumbersome and harder to maintain.

  • Context allows you to share data without manual prop passing, making code cleaner and more concise.

  • For data that needs to be accessed across multiple components, Context provides a convenient way to make it available globally.

Here's a comprehensive code example demonstrating how to use the Context API in React, along with explanations:

1. Create a Context file:

MyContext.js:

import React, { createContext } from 'react';

export const MyContext = createContext(/*put default value here*/); 
// the default value here is be undefined

2. Create a Provider Component:

App.js:

import React, { useState} from 'react';
import { MyContext } from './MyContext'
import ChildComponent from './ChildComponent'
export function App(props) {
  /** the value and setter of [text, setText] will be passed to 
     Child Component using Context */

  const [text, setText] = useState('state-default-value');
  return (
  <MyContext.Provider value={{text,setText}}>
    { /** we dont need to send text value to Child component, we will use it using useContext
       Check in ChildComponent.js
      */
     } 
    <ChildComponent></ChildComponent>
  </MyContext.Provider>
  );
}

3. Consume the Context in Child Components:

ChildComponent.js:

import React, { useContext } from 'react';
import { MyContext } from './MyContext';

function ChildComponent() {
  const { text, setText } = useContext(MyContext);

  return (
    <div>
      <h1>{text}</h1>
      <button onClick={() => setText('Hello, Context!')}>Change Text</button>
    </div>
  );
}

export default ChildComponent

Get the code Playground Here:
https://playcode.io/1730008

Explanation:

  • Creating a Context:

    • createContext(<default-value>) creates a context object to hold shared data.
  • Provider Component:

    • MyContext.Provider wraps the component tree that needs access to the context.

    • It provides the context value using the value prop.

    • It's often placed high in the component hierarchy for broader access.

  • Consuming the Context:

    • useContext hook extracts the context value in child components.

    • It takes the context object as an argument and returns its value.

Key Points:

  • Use Context for sharing data deeply without manually passing props through many levels.

  • Avoid excessive Context usage as it can make component relationships less clear.

  • Consider using state management libraries for complex data flows.

  • Remember that context values are not updated immediately in all consumers; React may batch updates for performance reasons.

Did you find this article valuable?

Support The art of Code by becoming a sponsor. Any amount is appreciated!