Home

usecontext

UseContext is a built-in React hook that lets functional components subscribe to React context. It reads the current value of a context and triggers a re-render whenever that value changes, without requiring a render prop or a Consumer component.

The hook takes a single argument: the context object created by React.createContext. Inside a component, you

Example: const ThemeContext = React.createContext('light'); function Toolbar(){ const theme = useContext(ThemeContext); return <div className={theme}>...</div>; }

Context can be consumed in multiple components and you can call useContext multiple times to read different

Performance and semantics: When a Provider’s value changes, all components that use that context re-render. This

Limitations: useContext can only be used in functional components or custom hooks. It cannot be used in

call
const
value
=
useContext(MyContext).
The
value
corresponds
to
the
nearest
Provider
above
in
the
component
tree;
if
there
is
no
matching
Provider,
the
defaultValue
specified
when
creating
the
context
is
used.
contexts.
can
lead
to
more
renders
if
the
value
changes
frequently,
so
it
is
common
to
keep
context
values
stable,
memoize
expensive
objects,
or
split
large
contexts
into
smaller
ones
to
minimize
unnecessary
updates.
class
components.
The
hook
relies
on
the
Context
API
and
requires
a
Provider
higher
in
the
component
tree
to
supply
the
value.