Function Components
Function components are a simplified version of normal components. They consist of a single function
that receives props and determines what should be rendered by returning Html
. Basically, it's a
component that's been reduced to just the view
method. On its own that would be quite limiting
because you can only create pure components, but that's where Hooks come in. Hooks allow function
components to maintain their own internal state and use other Yew features without needing to manually
implement the Component
trait.
Creating function components
The easiest way to create a function component is to add the #[function_component]
attribute to a function.
use yew::{function_component, html};
#[function_component(HelloWorld)]
fn hello_world() -> Html {
html! { "Hello world" }
}
Under the hood
There are two parts to how Yew implements function components.
The first part is the FunctionProvider
trait which is analogous to the Component
trait, except
that it only has a single method (called run
). The second part is the FunctionComponent
struct
which wraps types implementing FunctionProvider
and implements Component
.
The #[function_component]
attribute is a procedural macro which automatically implements
FunctionProvider
for you and exposes it wrapped in FunctionComponent
.
Hooks
Hooks are functions that let you "hook into" components' state and/or lifecycle and perform actions. Yew comes with a few pre-defined Hooks. You can also create your own.
Pre-defined Hooks
Yew comes with the following predefined Hooks:
use_state
use_state_eq
use_ref
use_mut_ref
use_node_ref
use_reducer
use_reducer_eq
use_effect
use_effect_with_deps
use_context
Custom Hooks
There are cases where you want to define your own Hooks for reasons. Yew allows you to define your own Hooks which lets you extract your potentially stateful logic from the 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 exactly the same as Yew's hooks, but the underlying concept is similar.