Advanced
React Context
Share state between components without prop drilling
- context
- local state
Key concepts
count
is a server prop, assigned on the LiveView exactly like
the Counter example. React's own createContext/useContext
then shares that value with a nested component with no prop passed
between them — the two mechanisms compose, they don't conflict.
defmodule MyAppWeb.ContextLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
{:ok, assign(socket, :count, 10)}
end
def render(assigns) do
~H"""
<.react name="Context" count={@count} socket={@socket} />
"""
end
def handle_event("set_count", %{"value" => value}, socket) do
{:noreply, assign(socket, :count, value)}
end
endHow it works
Context
wraps its children in a CountContext.Provider
whose value is the server-owned count
prop. Any component
inside that tree — however deeply nested — can call useContext(CountContext)
to read it, without every
component in between having to accept and forward a count
prop it doesn't otherwise need.
Clicking a button still calls pushEvent("set_count", …),
which reaches handle_event/3
and reassigns count
on the server, same as Counter — context describes how a value moves
around inside React, not where it comes from.