diff --git a/packages/docs/docs/getting-started.md b/packages/docs/docs/getting-started.md index ef07f77..5076eb5 100644 --- a/packages/docs/docs/getting-started.md +++ b/packages/docs/docs/getting-started.md @@ -167,6 +167,59 @@ export const GreetingCard = GreetingCardEffect.pipe( ) ``` +## Component Lifecycle + +Every Effect-FC component instance exposes an Effect `Scope`. Effects that need +`Scope.Scope` can use that component scope to register finalizers, fork scoped +work, or acquire scoped resources. + +The component scope is created when React mounts the component and closes when +React unmounts it. When the scope closes, Effect runs the finalizers registered +inside that scope. + +```tsx title="src/MountedMessageEffect.tsx" +import { Console, Effect } from "effect" +import { Component } from "effect-fc" + +export const MountedMessageEffect = Component.make("MountedMessage")( + function* () { + yield* Component.useOnMount(() => + Effect.gen(function* () { + yield* Console.log("MountedMessage mounted") + yield* Effect.addFinalizer(() => + Console.log("MountedMessage unmounted"), + ) + }), + ) + + return

This component owns an Effect scope.

+ }, +) +``` + +Use `Component.useOnMount` for work that should run once for the component +instance. Use `Component.useOnChange` when the scoped work should be recreated +when dependencies change. + +```tsx +const UserPanelEffect = Component.make("UserPanel")( + function* (props: { readonly userId: string }) { + const user = yield* Component.useOnChange( + () => fetchUser(props.userId), + [props.userId], + ) + + return

{user.name}

+ }, +) +``` + +In this example, changing `userId` closes the previous dependency scope before +creating a new one. Unlike `useOnMount`, `useOnChange` does not expose the component's root scope directly. +It creates and provides its own scope for that dependency window. Some other Effect-FC hooks +follow the same pattern when they need a lifecycle that is narrower than the +whole component instance. + ## Use Services Components can yield Effect services directly. Define services with Effect,