Hooks
A hook shares state and behavior between browser components. Each call has its own state. Here, each button increments its own counter and the reset button resets both.
hook useCounter(initial number) { state count = initial derived doubled = count * 2 func reset() { count = initial } return { count, doubled, reset } } comp Counters() { const first = useCounter(0) const second = useCounter(10) return <section> <p><button onClick={first.count++}>{first.count}</button> × 2 = {first.doubled}</p> <p><button onClick={second.count++}>{second.count}</button> × 2 = {second.doubled}</p> <button onClick={first.reset(); second.reset()}>Reset</button> </section> } document.body.append(<Counters />)
Call a hook with const name = hookName(args) in the body of a component or another hook. Read and write returned state as name.count. Returned derived values are read-only. Pass individual members when calling other functions.
Changes to arguments update the hook's parameters. A state initializer runs once per instance, so passing a new argument changes what reset()reads and keeps the current count. A hook's mount, effectand defer run with the component's lifecycle.
In server components, hooks can await data and defer cleanup.