Contexts

Usually, data is passed from a parent component to a child component via props. But passing props can become verbose and annoying if you have to pass them through many components in the middle, or if many components in your app need the same information. Context solve this problem by allowing a parent component to make data available to any component in the tree below it, no matter how deep, without having to pass it down with props.

The problem with props: “Prop Drilling”

Passing props is a great way to pass data directly from parent to a child. They become cumbersome to pass down through deeply nested component tree or when multiple components share the same data. A common solution to data sharing is lifting the data to a common ancestor and making the children take it as props. However, this can lead to cases where the prop has to go through multiple components in order to reach the component needs it. This situation is called “Prop Drilling”.

Consider the following example which passes down the theme using props:

  1. use yew::{html, Children, Component, Context, Html, Properties, function_component};
  2. #[derive(Clone, PartialEq)]
  3. pub struct Theme {
  4. foreground: String,
  5. background: String,
  6. }
  7. #[derive(PartialEq, Properties)]
  8. pub struct NavbarProps {
  9. theme: Theme,
  10. }
  11. #[function_component]
  12. fn Navbar(props: &NavbarProps) -> Html {
  13. html! {
  14. <div>
  15. <Title theme={props.theme.clone()}>
  16. { "App title" }
  17. </Title>
  18. <NavButton theme={props.theme.clone()}>
  19. { "Somewhere" }
  20. </NavButton>
  21. </div>
  22. }
  23. }
  24. #[derive(PartialEq, Properties)]
  25. pub struct ThemeProps {
  26. theme: Theme,
  27. children: Children,
  28. }
  29. #[function_component]
  30. fn Title(_props: &ThemeProps) -> Html {
  31. html! {
  32. // impl
  33. }
  34. }
  35. #[function_component]
  36. fn NavButton(_props: &ThemeProps) -> Html {
  37. html! {
  38. // impl
  39. }
  40. }
  41. /// App root
  42. #[function_component]
  43. fn App() -> Html {
  44. let theme = Theme {
  45. foreground: "yellow".to_owned(),
  46. background: "pink".to_owned(),
  47. };
  48. html! {
  49. <Navbar {theme} />
  50. }
  51. }

We “drill” the theme prop through Navbar so that it can reach Title and NavButton. It would be nice if Title and NavButton, the components that need access to the theme, can just access the theme without having to pass it to them as prop. Contexts solve this problem by allowing a parent to pass data, theme in this case, to its children.

Using Contexts

Step 1: Providing the context

A context provider is required to consume the context. ContextProvider<T>, where T is the context struct is used as the provider. T must implement Clone and PartialEq. ContextProvider is the component whose children will have the context available to them. The children are re-rendered when the context changes. A struct is used to define what data is to be passed. The ContextProvider can be used as:

  1. use std::rc::Rc;
  2. use yew::prelude::*;
  3. #[derive(Clone, Debug, PartialEq)]
  4. struct Theme {
  5. foreground: String,
  6. background: String,
  7. }
  8. #[function_component]
  9. fn NavButton() -> Html {
  10. let theme = use_context::<Theme>();
  11. html! {
  12. // use theme
  13. }
  14. }
  15. #[function_component]
  16. fn App() -> Html {
  17. let theme = use_memo(|_| Theme {
  18. foreground: "yellow".to_owned(),
  19. background: "pink".to_owned(),
  20. }, ());
  21. html! {
  22. <ContextProvider<Rc<Theme>> context={theme}>
  23. <NavButton />
  24. </ContextProvider<Rc<Theme>>>
  25. }
  26. }

Step 2: Consuming context

Function components

use_context hook is used to consume contexts in function components. See docs for use_context to learn more.

Struct components

We have 2 options to consume contexts in struct components:

Use cases

Generally, if some data is needed by distant components in different parts of the tree, it’s likely that context will help you. Here’s some examples of such cases:

  • Theming: You can put a context at the top of the app that holds your app theme and use it to adjust the visual appearance, as shown in the above example.
  • Current user account: In many cases, components need to know the current logged-in user. You can use a context to provide the current user object to the components.

Considerations to make before using contexts

Contexts are very easy to use. That makes them very easy to misuse/overuse. Just because you can use a context to share props to components multiple levels deep, doesn’t mean that you should.

For example, you may be able to extract a component and pass that component as a child to another component. For example, you may have a Layout component which takes articles as prop and passes it down to ArticleList component. You should refactor the Layout component to take children as props and display <Layout> <ArticleList {articles} /> </Layout>.

Mutating context value a child

Because of Rust’s ownership rules, a context cannot have a method that takes &mut self that can be called by children. In order to mutate a context’s value, we must combine it with a reducer. This is done by using the use_reducer hook.

The contexts example demonstrates mutable contexts with the help of contexts

Further reading