DEV Community

Cover image for Understanding React Context to Beginners or Lazy people 🥱
Pablo Obando
Pablo Obando

Posted on

16 3

Understanding React Context to Beginners or Lazy people 🥱

Do you know what's Context and how to use it with Hooks?

If you:

  • Doesn't understand the React Docs yet (in some moment you'll do it)
  • Only wants an explicit and easy tutorial 🦥

You're in the correct place!

What will be the path we will follow?

We're going to understand what is Context and what problem does it solve, then we're going through code!

Without further ado, let's do it 🏄‍♂️

In many applications, we have a state global (data which we need to manipulate in deferents parts of the app 💾)

Context, is a "state management" which provides a way to pass data through the component tree without having to pass props down manually at every level.

Now, we will through the steps to implement Context in our Apps

1- Creating our Context:

Code to create the Context Component

2- Subscribing our Components to the Context:

Every Context comes with a Provider, you need to wrap your components with the Provider this will allows to the components subscribe to the Context changes.

The Provider accepts a value prop to be passed to consuming components that are descendants

Context Provider

3- Consuming the Context in our component:

You can use a is a React component that subscribes to the Context changes which uses the "render props" technique to consume the value of the Context

In this example we're going to use the Hook useContext which accepts a Context object (the value returned from React.createContext) and returns the current Context value for that Context

Layout Component

Button Component

It's important to remember that the current Context value is determined by the value prop of the nearest above the calling component in the tree.

Well people this it's all, to this point I hope that you can create a Context, subscribed your components and change the current value of the Context since a child (look carefully out the second image of the step 3)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
rohansawant profile image
Rohan Sawant

I clicked for the yawning emoji!
Stayed for the good read.

The emoji, that's now a thing? 🤔

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more