top of page
Logo der Online Agentur mdwp

useContext

React Context, represented by the useContext hook, allows you to create global state variables that can be passed through components without having to pass the props through multiple levels. It is primarily used when some data needs to be accessible by many components at different nesting levels.

The useContext hook makes it easier to pass these values through the component tree without having to pass it through props. The Context is designed to share data that can be considered "global" for a tree of React components.

For instance:
```jsx
import React, { useContext } from 'react';

// First, creating a Context
const MyContext = React.createContext();

function App() {

// Use the MyContext provider to allow child components to use that Context
return (
<MyContext.Provider value="Hello, I'm the Context.">
<ChildComponent />
</MyContext.Provider>
);
}

function ChildComponent() {

// Inside the child component use useContext to consume the Context
const contextValue = useContext(MyContext);

return (
<p>{contextValue}</p>
);
}
```
In the example above we create a new Context, then use a Provider to allow child components to consume the value. In the ChildComponent we use useContext and pass the context object to consume the value. Then, we render the value in the paragraph tag.

bottom of page