Show List

Context API in React

The Context API in React is a way to pass data down the component tree without having to pass props down manually at every level. This allows for more efficient code, reduces prop drilling and makes sharing data between components easier.

Here's an example of how you can create a context and use it in your components:

// Create a context for data that will be shared between components
const UserContext = React.createContext({
  user: null,
  setUser: () => {}
});

// A component that provides the context value
function UserProvider({ children }) {
  const [user, setUser] = useState(null);

  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
}

// A component that uses the context value
function ProfilePage() {
  const { user, setUser } = useContext(UserContext);

  return (
    <div>
      <h1>Profile Page</h1>
      <p>{user ? `Welcome, ${user.name}` : "Please log in"}</p>
      <button onClick={() => setUser({ name: "John Doe" })}>Log in</button>
    </div>
  );
}

// Use the context provider at the top level of your component tree
function App() {
  return (
    <UserProvider>
      <ProfilePage />
    </UserProvider>
  );
}

In this example, we create a context called UserContext with a default value of { user: null, setUser: () => {} }. This context is then provided using the UserProvider component, which takes children as a prop and wraps them in the context provider. The ProfilePage component uses the useContext hook to consume the context and access the user and setUser values.

When the button is clicked in the ProfilePage component, the setUser function is called, which updates the user value in the context and re-renders the ProfilePage component with the updated value.

This is just a basic example of how you can use the Context API in React, but it should give you a good idea of how it works.


    Leave a Comment


  • captcha text