11import { signal } from "../signals/signals.ts" ;
22import { getCurrentContext } from "../component/context.ts" ;
3+ import { contextRegistry } from "../context/registry.ts" ;
4+ import type { ComponentContext } from "../context/types.ts" ;
35
46// Why: Implements useState hook with signal integration
57export function useState < T > ( initialValue : T ) : [ T , ( value : T ) => void ] {
68 const context = getCurrentContext ( ) ;
79 if ( ! context ) throw new Error ( "useState must be called within a component" ) ;
810
11+ // Register hook in context registry
12+ const hookId = contextRegistry . generateId ( "hook" , context . id ) ;
913 const hookIndex = context . hookIndex ++ ;
1014
1115 if ( ! context . hooks [ hookIndex ] ) {
1216 const sig = signal ( initialValue ) ;
13- context . hooks [ hookIndex ] = sig ;
17+ context . hooks [ hookIndex ] = { id : hookId , signal : sig } ;
1418 context . signals . add ( sig ) ;
19+
20+ // Register cleanup in context
21+ context . cleanup . add ( ( ) => {
22+ context . signals . delete ( sig ) ;
23+ } ) ;
1524 }
1625
17- const sig = context . hooks [ hookIndex ] ;
26+ const { signal : sig } = context . hooks [ hookIndex ] ;
1827 return [ sig . value , ( value : T ) => sig . set ( value ) ] ;
1928}
2029
@@ -23,9 +32,10 @@ export function useEffect(
2332 effect : ( ) => void | ( ( ) => void ) ,
2433 deps ?: any [ ] ,
2534) : void {
26- const context = getCurrentContext ( ) ;
35+ const context = getCurrentContext ( ) as ComponentContext ;
2736 if ( ! context ) throw new Error ( "useEffect must be called within a component" ) ;
2837
38+ const hookId = contextRegistry . generateId ( "hook" , context . id ) ;
2939 const hookIndex = context . hookIndex ++ ;
3040 const oldDeps = context . hooks [ hookIndex ] ;
3141
@@ -43,9 +53,17 @@ export function useEffect(
4353 const cleanup = effect ( ) ;
4454 if ( typeof cleanup === "function" ) {
4555 context . cleanup . add ( cleanup ) ;
56+
57+ // Register in context registry
58+ contextRegistry . setContext ( hookId , {
59+ type : "hook" ,
60+ id : hookId ,
61+ cleanup : new Set ( [ cleanup ] ) ,
62+ parent : context ,
63+ } ) ;
4664 }
4765
48- context . hooks [ hookIndex ] = { deps, cleanup } ;
66+ context . hooks [ hookIndex ] = { id : hookId , deps, cleanup } ;
4967 }
5068}
5169
0 commit comments