Using hooks
Hooks give a component state, effects, memoised values and context access. They are declared by call order, so every render must call the same hooks in the same order.
Rules of hooks
- Call hooks only from
Render. - Call them unconditionally, in the same order on every render.
- Do not call them from loops, conditions or nested local functions.
- Conditional output belongs in the returned tree, not around a hook call.
public override Node Render()
{
var (visible, setVisible) = State(false);
var (count, setCount) = State(0);
return H("div", null,
Show(visible, H("span", Text(count.ToString()))));
}
State
State<T> returns the current value and a setter. Setters
mark the component dirty; the renderer applies the update after the current
handler or effect finishes.
public sealed class Counter : Component
{
public override Node Render()
{
var (count, setCount) = State(0);
return H("button", new Props
{
ClassName = "counter",
OnClick = () => setCount(count + 1)
}, Text($"Clicked {count} times"));
}
}
Functional updates
Use StateWithUpdate when the next value depends on the
previous one, especially when several updates happen in one handler.
var (count, setCount, updateCount) = StateWithUpdate(0);
updateCount(value => value + 1);
updateCount(value => value + 1);
The first render can also be lazy: pass () => CreateInitial()
to either State or StateWithUpdate. The factory
runs once, when the hook slot is created.
Reducer
Reducer is useful when state transitions have names or several
fields change together.
public sealed record EditorState(string Text, bool Dirty);
public abstract record EditorAction
{
public sealed record Edit(string Text) : EditorAction;
public sealed record Save : EditorAction;
}
public override Node Render()
{
var (state, dispatch) = Reducer<EditorState, EditorAction>(
new EditorState("", false),
(current, action) => action switch
{
EditorAction.Edit edit => current with { Text = edit.Text, Dirty = true },
EditorAction.Save => current with { Dirty = false },
_ => current
});
return H("input", new Props
{
Value = state.Text,
OnInput = text => dispatch(new EditorAction.Edit(text))
});
}
Effects
Effects run after the virtual tree has been applied and the renderer has committed it. Use the dependency list to control when they run.
| Call | When it runs |
|---|---|
Effect(action) | After every commit. |
Effect(action, deps) | After a commit where a dependency value changed. |
Effect(action, []) | Once after mount. |
Effect(Func<Action?>) | After every commit; the returned action is the cleanup. |
Effect(Func<Action?>, deps) | When dependencies change; the previous cleanup runs first. |
public override Node Render()
{
Effect(() =>
{
var connection = Connect(endpoint);
return () => connection.Dispose();
}, [endpoint]);
return H("p", Text("Connected"));
}
Dependency arrays are compared element by element. An empty array has no elements to differ, so it runs once. Arrays are stored by reference, so do not mutate a dependency array after passing it.
Layout effects
LayoutEffect runs synchronously during commit, after the tree
is patched but before passive effects. Use it for measurements or
adjustments that the next frame should see.
LayoutEffect(() =>
{
// Runs after the tree is applied and before passive effects.
}, []);
Memo and callbacks
Memo caches an expensive value and recomputes when a
dependency changes. Callback does the same for a delegate,
which is useful when passing handlers to children.
var summary = Memo(
() => BuildSummary(items),
items.Length);
var save = Callback(
() => Save(name, email),
name, email);
Refs
UseRef returns the same mutable holder across renders. Writes
to it do not schedule a render, so it is useful for timers, subscriptions
and other values that should not participate in rendering.
var firstRun = UseRef(true);
Effect(() =>
{
if (firstRun.Value)
{
firstRun.Value = false;
// one-time setup
}
}, []);
Context
UseContext(Context<T>) reads the nearest provider value,
or the context default when no provider is in scope. The value is resolved
from the scope captured when the component last rendered.
var theme = UseContext(ThemeContext.Value);
return H("main", new Props
{
Attributes = new Dictionary<string, string>
{
["style"] = $"background:{theme.Background}"
}
});
Creating a provider covers the publisher side and nesting rules.
Lifecycle overrides
Components also expose virtual lifecycle methods when an effect is not the right shape.
| Method | When it runs |
|---|---|
OnMount() | After the first commit. |
OnUpdate() | After a re-render; not called when ShouldRender vetoes it. |
OnUnmount() | When the component leaves the tree. |
ShouldRender() | Return false to skip a parent-driven render; own state updates are not vetoed. |
public sealed class Page : Component
{
protected override void OnMount()
{
// Called after the first commit.
}
protected override void OnUpdate()
{
// Called after a re-render.
}
protected override void OnUnmount()
{
// Called when the component leaves the tree.
}
}
Props
Use Component<TProps> when a component receives props.
The renderer assigns Props before calling
Render and again on every parent render.
public sealed class GreetingProps : Props
{
public string Name { get; init; } = "";
}
public sealed class Greeting : Component<GreetingProps>
{
public override Node Render() =>
H("p", Text($"Hello, {Props.Name}"));
}