Skip to content

useSignal should not use useMemo #307

Description

@reosablo

The current implementation of useSignal uses useMemo.

export function useSignal<T>(value: T) {
return useMemo(() => signal<T>(value), Empty);
}

React document says to write the code so that it still works without useMemo. Preact might be the same.

You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

Without useMemo, useSignal will create a new signal instance every time when re-rendering occurs and lose the previous value.

Also, useComputed uses useMemo. There's no problem I think.

export function useComputed<T>(compute: () => T) {
const $compute = useRef(compute);
$compute.current = compute;
return useMemo(() => computed<T>(() => $compute.current()), Empty);
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions