React Context API: A Hilarious Journey into State Management 🚀
Tags: webdev, contextapi, react, statemanagement
Published: 2024-04-30 07:15:42

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]](https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/). 

_Prop-Drilling_: The nightmare scenario where you pass props down through multiple layers of components, akin to navigating a maze blindfolded.
![prop-drilling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04rgv2e25ksi28q53ta4.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6l3pxlfzj76yao5f6qc.png)
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnwsidum9h6hrze9okg0.png)](https://dmitripavlutin.com/90649ae4bdf379c482ad24e0dd220bc4/react-context-3.svg)

**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');
```
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>
  );
}
```
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>;
}
```
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>
  );
}
```

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/) - https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/
[[2]](https://dmitripavlutin.com/react-context-and-usecontext/) - https://dmitripavlutin.com/react-context-and-usecontext/
[[3]](https://www.freecodecamp.org/news/context-api-in-react/) - https://www.freecodecamp.org/news/context-api-in-react/
[[4]](https://react.dev/reference/react/createContext) - https://react.dev/reference/react/createContext