top of page
Logo der Online Agentur mdwp

Context

In React.js, Context is a concept that helps you pass data through the component tree without having to pass props down manually at every level. It is primarily used when some data needs to be accessible by many components at different levels in the application.

Context provides a way to pass data directly from a parent component to a child component or from a child component to a grandchild component with no need to pass down props through intermediary components. This makes the code cleaner and easier to understand.

Here is a basic usage of Context:

Firstly, you create a Context object:

```javascript
const MyContext = React.createContext(defaultValue);
```
'`defaultValue`' is only used when a component does not have a matching Provider above it in the tree.

Then, create a context provider component. This component will 'provide' the context value to child components:

```javascript
<MyContext.Provider value={/* some value */}>
```
Lastly, read the current context value from a context consumer. A component that needs the context value should be a 'descendant' of a provider for this context:

```javascript
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
```
Or you can use the `useContext` hook:

```javascript
const value = useContext(MyContext);
```
With Context, you avoid 'prop drilling', where you have to pass props through every level of the component tree before it reaches the components that use the props. It makes data flow in the app more maintainable and efficient.

bottom of page