Skip to content

@epikodelabs/streamix


@epikodelabs/streamix / react/src/public-api / useScope

Function: useScope() ​

useScope<T>(factory): T

Defined in: projects/libraries/streamix/react/src/lib/useScope.ts:36

Creates a streamix Scope whose lifetime is tied to the component.

factory runs once, lazily, on the first render. Every atom, derived value, or nested scope created inside it is disposed automatically when the component unmounts — you never need to write manual teardown for state that lives inside the returned scope.

The factory is not re-run when the component re-renders; pass stable (or already-memoized) inputs into it, the same way you would with useState(() => ...).

Type Parameters ​

T ​

T extends Record<string, any>

Parameters ​

factory ​

() => T

Returns ​

T

Example ​

tsx
function Counter() {
  const state = useScope(() => scope({
    count: 0,
    doubled: (self: any) => self.count * 2,
  }));

  const [count, setCount] = useWritable(state.get('count'));
  const doubled = useIterable(state.get('doubled'));

  return (
    <button onClick={() => setCount(count + 1)}>
      {count} (doubled: {doubled})
    </button>
  );
}

Released under the MIT License.