React Context API: A Hilarious Journey into State Management πŸš€

sulavgaire

Sulav Gaire

Posted on April 30, 2024

React Context API: A Hilarious Journey into State Management πŸš€

Welcome, Fellow developers, to the wild and wacky world of React Context API, where state management becomes an adventure filled with laughter, tears, and a few console.log() statements thrown in for good measure. Today, we embark on a journey through the depths of React's state management. Strap in, because this is going to be one heck of a ride!πŸŽ‰


Chapter 1 - In the Beginning, There Was State

Once upon a time, in the land of React, developers found themselves faced with a common dilemma: how to manage state efficiently across multiple components without descending into madness of prop-drilling [1].

Prop-Drilling: The nightmare scenario where you pass props down through multiple layers of components, akin to navigating a maze blindfolded.
prop-drilling

Enter the hero of our story: the Context API. With its magical powers, it promised to solve all our state management woes and bring peace to the kingdom of React. πŸ’‘

using Context API

Chapter 2: Unveiling the Context API

Discovering the Context API is like finding a treasure map in a sea of code. It offers global state management and component bliss. 🌟

Three steps to use the context:

  1. Creating the context
  2. Providing the context
  3. Consuming the context

Context API

A. Creating the context
The built-in factory function createContext(default) creates a context instance:

// context.js
import { createContext } from 'react';

export const Context = createContext('Default Value');
Enter fullscreen mode Exit fullscreen mode

The factory function accepts one optional argument: the default value.

B. Providing the context
Context.Provider component available on the context instance is used to provide the context to its child components, no matter how deep they are. (No more prop drilling)

To set the value of context use the value prop available on the <Context.Provider value={value} />:

import { Context } from './context';

function Main() {
  const value = 'My Context Value';
  return (
    <Context.Provider value={value}>
      <MyComponent />
    </Context.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Again, what's important here is that all the components that'd like later to consume the context have to be wrapped inside the provider component.

If you want to change the context value, simply update the value prop.

C. Consuming the context
Consuming the context can be performed in 2 ways.

The first way, the one I recommend, is to use the useContext(Context) React hook:

import { useContext } from 'react';
import { Context } from './context';

function MyComponent() {
  const value = useContext(Context);

  return <span>{value}</span>;
}
Enter fullscreen mode Exit fullscreen mode

The hook returns the value of the context: value = useContext(Context). The hook also makes sure to re-render the component when the context value changes.

The second way is by using a render function supplied as a child to Context.Consumer special component available on the context instance:

import { Context } from './context';

function MyComponent() {
  return (
    <Context.Consumer>
      {value => <span>{value}</span>}
    </Context.Consumer>
  );
}
Enter fullscreen mode Exit fullscreen mode

Again, in case the context value changes, <Context.Consumer> will re-call its render function.

You can have as many consumers as you want for a single context. If the context value changes (by changing the value prop of the provider <Context.Provider value={value} />), then all consumers are immediately notified and re-rendered.

If the consumer isn't wrapped inside the provider, but still tries to access the context value (using useContext(Context) or <Context.Consumer>), then the value of the context would be the default value argument supplied to createContext(defaultValue) factory function that had created the context.
With the Consumer component, accessing context values becomes a breeze. Say goodbye to prop drilling and hello to context goodness. πŸ¦Έβ€β™‚οΈ

Chapter 3: The Future of Context

As our adventure ends, we ponder the Context API's future. Will it remain king, or will new challengers arise? One thing's certain: React devs will always hold it dear. ❀️

Some common use cases are:

  • global state
  • theme
  • application configuration
  • authenticated user name
  • user settings
  • preferred language
  • a collection of services

note: Zustand, Redux are also used for state management

Conclusion:

Our journey through React's Context API ends with laughter, tears, and a laptop or two tossed in frustration. But with each challenge conquered, we find joy in the endless possibilities of web development. Happy coding, fellow adventurers! πŸš€πŸŽ‰


Refrences

[1] - https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/
[2] - https://dmitripavlutin.com/react-context-and-usecontext/
[3] - https://www.freecodecamp.org/news/context-api-in-react/
[4] - https://react.dev/reference/react/createContext

πŸ’– πŸ’ͺ πŸ™… 🚩
sulavgaire
Sulav Gaire

Posted on April 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related