Have you ever had to pass a piece of data from one parent component to one child, and then to another, and to another... just to use it in the end? This is what is known as “prop drilling” 😵
Okay, React Context API It's like telling your app:
“Hey, this data is important, make it accessible to everyone without having to pass it by hand through each component.”
🏠 A quick analogy
Imagine that you live in a house with 10 rooms (components). And there is only one remote control (global status). Are you going to go piece by piece passing it on to everyone?
No! You'd better leave it on the living room table (Context), and anyone who needs it, goes and grabs it 🙌
🌗 Example: light mode/dark mode
Let's say your app has two themes: stark and sombre. You don't want to prop up all the buttons, backgrounds, headers, etc. You'd better create a ThemeContext
and that's it.
And now anywhere in the app you can use it like this:
You connect everything like this:
❌ When? NO should you use Context?
Although Context is cool, It's not for everything:
- If the data changes all the time (like what you write in an input) 👉 it becomes slow, because it re-renders everything.
- If you only need 1 or 2 components nearby 👉 it's better to use props.
- If your app is big and you need to handle a lot of global things 👉 maybe it's time to look at things like Zustand, Redux or Recoil.
✅ In short
Context API = seamless global info sharing.
Useful for things like:
- Light/dark mode 🌗
- Language 🌍
- Logged in user 👤
But don't abuse. If you get more complicated than you solve... better another tool 😅
Does your company need to strengthen its infrastructure, scale its applications and optimize the development experience? 👉 Contact us and we advise you on how to implement Google Cloud with security, performance and productivity.