yew/website/docs/concepts/function-components.md
mc1098 ed2e1ea00e
Add testing for website code blocks (#2014)
* Add doc-test to test website code snippets

Heavily inspired by tokio-rs/website repo.

* Fix code snippets to pass doc tests

Some code snippets are explicitly ignored and some are not run
to avoid having to include dependencies for one liners.

* Add website code snippet tests to CI

* Fix CI

* Remove doc-test from workspace

* Exclude doc-test from workspace

* Refactor code snippets and tests

Code snippets can import types from doc_test crate i.e.:
```rust
use doc_test::agents::EventBus;
```
This allows for moving some boilerplate away from the example and still
checks that the code compiles correctly.

Also some slight changes to some of the examples and the information
about `ComponentLink` which is deprecated.

* Move doc-test to packages

* Rename doc-test crate to website-test

The new name makes it more clear the purpose of this crate.

* fix ci
2021-08-28 13:17:28 +02:00

2.4 KiB

title sidebar_label description
Function Components Introduction Introduction to 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 use state and other Yew features without implementing 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

Function components consists of two parts. First, the FunctionProvider trait which is comparable to the Component trait but it only has a single method called run. The second part is the FunctionComponent struct which wraps around the FunctionProvider type and turns it into an actual Component. The #[function_component] attribute essentially just implements FunctionProvider for you and exposes it wrapped in FunctionComponent.

Hooks

Hooks are simply 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:

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.