UseGoRoutine manages a goroutine lifecycle within a component. It spawns a new goroutine with the provided function when dependencies change, and automatically cancels the context on dependency changes or component unmount. This hook must be called within a component context.
(fn func(ctx context.Context), deps []any)
| 145 | // and automatically cancels the context on dependency changes or component unmount. |
| 146 | // This hook must be called within a component context. |
| 147 | func UseGoRoutine(fn func(ctx context.Context), deps []any) { |
| 148 | rc := engine.GetGlobalRenderContext() |
| 149 | if rc == nil { |
| 150 | panic("UseGoRoutine must be called within a component (no context)") |
| 151 | } |
| 152 | |
| 153 | // Use UseRef to store the cancel function |
| 154 | cancelRef := UseRef[context.CancelFunc](nil) |
| 155 | |
| 156 | UseEffect(func() func() { |
| 157 | // Cancel any existing goroutine |
| 158 | if cancelRef.Current != nil { |
| 159 | cancelRef.Current() |
| 160 | } |
| 161 | |
| 162 | // Create new context and start goroutine |
| 163 | ctx, cancel := context.WithCancel(context.Background()) |
| 164 | cancelRef.Current = cancel |
| 165 | |
| 166 | componentName := "unknown" |
| 167 | if rc.Comp != nil && rc.Comp.Elem != nil { |
| 168 | componentName = rc.Comp.Elem.Tag |
| 169 | } |
| 170 | |
| 171 | go func() { |
| 172 | defer func() { |
| 173 | util.PanicHandler(fmt.Sprintf("UseGoRoutine in component '%s'", componentName), recover()) |
| 174 | }() |
| 175 | fn(ctx) |
| 176 | }() |
| 177 | |
| 178 | // Return cleanup function that cancels the context |
| 179 | return func() { |
| 180 | if cancel != nil { |
| 181 | cancel() |
| 182 | } |
| 183 | } |
| 184 | }, deps) |
| 185 | } |
| 186 | |
| 187 | // UseTicker manages a ticker lifecycle within a component. |
| 188 | // It creates a ticker that calls the provided function at regular intervals. |
no test coverage detected