`useContext` is a built-in hook in React that allows you to consume a context in functional components. Context is a way to pass data down the component tree without having to manually pass props through every level of the tree.
Here’s an example of how to use `useContext` to consume a context:
jsx import React, { useState, useContext } from "react"; const MyContext = React.createContext(); function ParentComponent() { const [value, setValue] = useState("Hello, world!"); return (); } function ChildComponent() { const value = useContext(MyContext); return {value}
; }
In this example, we’re defining a context called `MyContext` using the `React.createContext()` method. We’re then defining a `ParentComponent` that sets the value of the context to `”Hello, world!”` using the `MyContext.Provider` component. We’re also defining a `ChildComponent` that uses `useContext` to consume the value of the context.
The `useContext` function takes a context object as its argument and returns its current value. In this example, we’re passing `MyContext` as the argument to `useContext` in `ChildComponent`, which returns the current value of the context (`”Hello, world!”`).
You can also use `useContext` to consume multiple contexts in a single component. Here’s an example of how to use `useContext` to consume two contexts:
jsx import React, { useState, useContext } from "react"; const ThemeContext = React.createContext("light"); const LanguageContext = React.createContext("en"); function ParentComponent() { return (); } function ChildComponent() { const theme = useContext(ThemeContext); const language = useContext(LanguageContext); return ( ); }Theme: {theme}
Language: {language}
In this example, we’re defining two contexts (`ThemeContext` and `LanguageContext`) and a `ParentComponent` that sets the values of both contexts using `ThemeContext.Provider` and `LanguageContext.Provider`. We’re also defining a `ChildComponent` that uses `useContext` to consume both contexts and render their values.
Overall, `useContext` is a powerful tool in React that allows you to consume contexts in functional components and build flexible and reusable user interfaces. By using `useContext`, you can create components that rely on shared data, settings, or themes without having to pass props down the component tree.