Context API Simplified.
Table of contents
Previously, I talked about why people encounter a lot of bugs and how to prevent them.
Recently, I was exploring one of the most confusing topics in React: the Context API. My initial reaction was, "What's all this rubbish?" I thought I could grasp the concept quickly, but the more I learned and researched, I was surprised by the implementation. Without using props, we can pass data and get the job done, and I found it to be a much better approach.
Almost every web developer who uses React for development utilizes the Context API to manage components. It's generally used with a hook called useContext
.
Let's try to understand with the image given below. For instance, I have eight components in my React app, and I want to change or add a color to my component C8
. My props would have to travel from one component to another, which I consider a bad practice (just for changing the color).
Analyze here.
But when I use the Context API as a hook, e.g.,
const value = useContext(SomeContext)
Then we just have to use the wrapper.Provider
(your variable's name) for our App.jsx
to add the components to it. The image below shows how easy it has become for us now to add new features to the components.
There are two ways of doing it:
Create a JavaScript file, export the
useContext
variable, and save it.Create a
UseContext
file, write the functionality, and get it done.
The optimized approach:
Creating a single file for everything:
export const ThemeGiver = createContext({
themeMode: "Light",
Dark: () => {},
Light: () => {}
})
// Wrapper for our context
export const ThemeProvider = ThemeGiver.Provider
// Creating a custom hook
// All the work done in a single file
export default function useTheme() {
return useContext(ThemeGiver);
}
Later, just wrap it and access its values easily. 🍿
What we get:
Direct communication
Works with the flow to and fro
Saves time (nothing more to say)
All it asks for is you investing a little time out of your comfort zone.
Conclusion
It's possible to create apps without it, but all it costs is your time and computer memory (nothing else).
Keep moving forward.
Subscribe to my newsletter
Read articles from Kartik Doda directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by