Callbacks should be made within the lifetime of the component's scope

Open
#1,656 1 comment 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
rust
Domain
frontend, web-dev

Research direction

The issue names functional components, yew_functional::use_state, useCallback, hooks, and component scope; begin by tracing those APIs and how their lifetimes are handled. Done means callbacks can borrow hook data for the component lifetime without requiring 'static or cloning captured values, including the shown pattern.

Written by the indexing model from the issue text.

Description

A-yew feature-request

Describe the feature you'd like
Currently, callbacks made within functional components are annoying to work with. The requirements on callback don't necessarily require 'static, but are pretty much 'static. Note, this means that closures can't contain references to borrowed data, meaning any values used by other state mechanisms need to be cloned into the closure.

However, this wouldn't be necessary if the callbacks could borrow data from other hooks. We can't set the lifetime to be that of the function component itself, but if the data borrowed from the hooks could share the lifetime of the scope, then we could do something along these lines:

fn test_element() {
    let (dragging, set_dragging) = yew_functional::use_state(|| false);
    let g = RefCell::new(dragging);
    let r = &g;

    let a1 = useCallback(move || println!(r.borrow())));
    let a2 = useCallback(move || println!(r.borrow()));
    let a3 = useCallback(move || println!(r.borrow()));
}

From there I imagine we could wrap the hooks in an interface like RefCell that also updates the hook and component.

I'm not 100% sure on where the lifetime would be coming from, since there's no lifetime provided to functional components (instead relying on thread-locals). I imagine we could get a lifetime either when the app is launched (effectively being static) or on the creation of components.

Questionnaire

  • I'm interested in implementing this myself but don't know where to start
  • I would like to add this feature
  • I don't have time to add this right now, but maybe later
Dominant language
Rust
Stars
32.8k
Forks
1.5k
Avg merge
5h 34m
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from yewstack/yew

All issues in yewstack/yew

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.