Skip to content
Search

React:Context

lastmod 2024-01-25created 2024-01-222 edits

Context is designed to share data that can be considered "global" for a tree of React components. Such data includes the current authenticated user, theme, or preferred language.

Example

import React from 'react';
export const UserContext = React.createContext();
export default function App() {
  return (
    <UserContext.Provider value="Reed">
      <User />
    </UserContext.Provider>
  )
}
function User() {
  const value = React.useContext(UserContext);  

  return <h1>{value}</h1>;
}

How to use in NextJS

Must be used in a client component.

'use client';

import { createContext } from 'react';

const Context = createContext();

See also

Favorite site

author Zer0 sitemap