top of page
Logo der Online Agentur mdwp

Context API

React Context API is a feature offered in React.js that enables you to share some data or functionality across multiple components, without having to pass it manually at every level, i.e., via props. This is particularly useful when you have data that needs to be accessible by many components at different nesting levels or when you have to pass data through a component that otherwise wouldn't use the data itself.

An example of a common data that might be managed by the Context API could be the currently logged-in user's information.

Consider this basic example:

First, create a context.

const UserContext = React.createContext();

Then use a Context Provider to wrap your components. The provider takes a `value` prop to be passed to consuming components that are descendants of this provider.

<usercontext.provider value="{currentUser}">
/* ... other components ... */

Within a functional component where you want to access this context value, you can use the `useContext` hook.

function NavigationBar() {
const user = useContext(UserContext);

return (
{`Hello, ${}!`}

In the above example, the `NavigationBar` component get the current user's information from the context, and use it to display a personalized greeting. This happens regardless of where in the component tree `NavigationBar` is. This makes it easier to manage global state and propagate it through your component tree.

bottom of page