DEV Community

Cover image for React Context API
Shubham Tiwari
Shubham Tiwari

Posted on

React Context API

Hello everyone, today I'll show you how to create a single state for data that can be used in any component down the Component tree without the use of props.

Let's get started...

Issue with props -

  • When you create a state in react using state and want to pass that state to another component, such as a parent-child relationship, you pass the state data as a prop to the other component, and everything works fine.
  • The issue arises when you attempt to pass that state data down to another component that is deeply nested within another component. It will force the component to receive unrelated data in order to pass it down to the component tree, which may result in unnecessary re-rendering.
  • To solve this problem, we can use context API in react. # createContext -
import { createContext, useContext, useState, useRef } from "react";
const UserContext = createContext();
export default function App() {
  const [username, setUsername] = useState({ id: 101, name: "Shubham" });
  return (
    <div className="App">
      <UserContext.Provider value={[username, setUsername]}>
        <h1>Main Component 1</h1>        
        <ReadUser1 />
      </UserContext.Provider>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • In this example, I've used "createContext" to create a context that will be used by assigning a value to it in the Provider.
  • As an array value, I passed the state and its setter function.
  • This array will be received directly by both Components within UserContext.

useContext -

const ChangeUser = () => {
  const globalData = useContext(UserContext);
  const [username, setUsername] = globalData;
  const inputRef = useRef(null);
  return (
    <div>
      <h2>Component 2 inside Component 1</h2>
      <input type="text" ref={inputRef}/>
      <button
        onClick={() => {
          if(username.name !== inputRef.current.value){
          setUsername({id:Math.floor(Math.random() * 9999999),name:inputRef.current.value})
          }
          inputRef.current.focus()
        }}
      >
        Change Username
      </button>
      <ReadUser />
    </div>
  );
};

const ReadUser = () => {
  const globalData = useContext(UserContext);
  const [username] = globalData;
  return (
    <div>
      <h2>Component 3 inside Component 2</h2>
      <h2>{username.id}</h2>
      <h2>{username.name}</h2>
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode
  • We can obtain the value returned by createContext by using useContext.
  • I extracted the state and its setter function from the array value using array destructuring.
  • I'm changing the state in the App component in the ChangeUser component and then showing the value in the ReadUser component, which is inside the ChangeUser component.
  • As you can see I can access the state and its setter function in any component inside Context Provider. Best part is i can use this ReadUser component anywhere even outside the ChangeUser component

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me with some donations at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/css-iswherehas-and-not-2afd

https://dev.to/shubhamtiwari909/theme-changer-with-html-and-css-only-4144

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90

Top comments (0)