Hooks
Hooks#
Hooks are functions that let you store state and perform side effects.
Yew comes with a few pre-defined hooks. You can also create your own or discover many community-made hooks.
Rules of hooks#
- A hook function name always has to start with
use_ Hooks can only be used in the following locations:
- Top-level of a function/hook.
- Blocks inside a function/hook, given it is not already branched.
- In the condition of a top-level
ifexpression inside a function/hook. - In the scrutinee of a top-level
matchexpression inside a function/hook.
- Hooks must be called in the same order for every render. Returning early is only allowed when using Suspense
These rules are enforced by either compile-time or run-time errors.
Pre-defined Hooks#
Yew comes with the following predefined Hooks:
use_stateuse_state_equse_memouse_callbackuse_refuse_mut_refuse_node_refuse_reduceruse_reducer_equse_effectuse_effect_withuse_contextuse_force_update
The documentation for these hooks can be found in the Yew API docs
Custom Hooks#
There are cases where you want to define your own Hooks to encapsulate potentially stateful logic from a component into reusable functions. See the Defining custom hooks section for more information.
Further reading#
- The React documentation has a section on React hooks. These are not the same as Yew's hooks, but the underlying concept is similar.