user13028389
user13028389

Reputation:

how to consume multiple context in reactjs

Is it possible to consume multiple context in one component which is from two different component . I tried It but but I am not getting value This is the component which consume two different context

import React from "react";
import { UserContext } from "../App";
import { NewContext } from "./CompY";

const CompX = () => {
  return (
    <div>
      <UserContext.Consumer>
        {(user) => {
          return (
            <>
              <NewContext.Consumer>
                {(username) => {
                  return (
                    <>
                      <h1>Hello {user.username} </h1>
                      <h2>This is CompX in the {user.name} component</h2>
                      <h3>This is {username} </h3>
                    </>
                  );
                }}
              </NewContext.Consumer>
            </>
          );
        }}
      </UserContext.Consumer>
    </div>
  );
};
export default CompX;

Here is the App.Js

Upvotes: 0

Views: 117

Answers (1)

Nisharg Shah
Nisharg Shah

Reputation: 19692

You can use multiple contexts in functional component easily with useContext

Consumer and provider is bad practice in functional component

import { UserContext } from "../App";
import { NewContext } from "./CompY";

const CompX = () => {
    const user = useContext(UserContext);
    const newUser = useContext(NewContext);

    ....
}

Upvotes: 1

Related Questions