My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

use context?

Shanu Agrawal's photo
Shanu Agrawal
·Mar 1, 2022·

2 min read

This is my 2nd blog, Today I focus on Context API of react. I will let you know, how components interact with each other in App. As we know that React is JavaScript library. It is used to build User Interface. if we break any React App, it will dispersed into different different components.

Why Context API

Earlier it becomes tedious to pass data from one component to another. And it was very time consuming, Imagine a situation, there is queue of 10 people. I need to send the parcel to last one in the queue, but parcel goes through to every person in the queue. And with the useContext API, We can directly pass the parcel to the last one, without passing through intermediary one. woww that's cooll!!

Implementation

Lets see now, how we can implement Context in our react app I made a toggle button which is used to change theme of App by the use of Context API, Let me show the process

  • Import Context from react
import { createContext } from "react";
  • Create the Context
const ThemeContext = createContext();
  • provide the Provider to the context that wraps the main app -> Actually use of provider is to gets the data from the global context and pass to the consumer.
 const ThemeProvider = ({children}) => {
  const[theme,setTheme] = useState("light")

   return (
     <ThemeContext.Provider value ={{theme,setTheme}}>
     {children}
     </ThemeContext.Provider>

   )
 }
  • how provider wraps the main app (in index.js file)
ReactDOM.render(
  <StrictMode>
    <ThemeProvider>
    <App />
    </ThemeProvider>
  </StrictMode>,
  rootElement
);
  • Now we have data in our global context, now any components can easily consume the data through useContext
  const {theme,setTheme} = useContext(ThemeContext);
  • now Components are happy, because now they easily consume the data, directly from the global state

ThemeProject(codesandbox)

This is whole process of working of Context API. For better learning, try to think practical -> like think components as a Human beings and App is a Society. Now Society need to pass a information for a particular human being. so you think should I pass to every person in between till the consumer. or should I make a platform where any person can check their information separately.

  • Thank you

  • Happy Coding :)