Skip to content

explain why you may want to return a function from a resource, instead of just returning a value. #946

@NullVoxPopuli

Description

@NullVoxPopuli

Example:

const Clock = resource(({ on }) => {
  const now = cell(Date.now());
  const interval = setInterval(() => now.current = Date.now(), 1000);
  on.cleanup(() => clearInterval(interval));

  return now.current;
})

vs

const Clock = resource(({ on }) => {
  const now = cell(Date.now());
  const interval = setInterval(() => now.current = Date.now(), 1000);
  on.cleanup(() => clearInterval(interval));

  return () => now.current;
})

The reason:

  • because the tracked data (.current), would be immediately consumed in the resource() body, the whole thing would be torn down when the clock updates (create a new interval each second). By using a function, only the function invalidates, you retain state, and keep the interval.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions