Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created August 21, 2024 15:19
Show Gist options
  • Save mattmccray/4c9eb04a848316b4533018a474d5bd47 to your computer and use it in GitHub Desktop.
Save mattmccray/4c9eb04a848316b4533018a474d5bd47 to your computer and use it in GitHub Desktop.
Simple Controller Hook
import { useEffect, useMemo } from "react" // or "preact/hooks"
type ConstructorParams<T extends new (...args: any) => any> = T extends new (
...args: infer P
) => any
? P
: never
/**
* A simple view controller react hook. This hook will create a new
* instance of the controller when the component is mounted and
* dispose the controller when the component is unmounted. The
* controller will be created with the given params, and re-created
* when the params change. If the controller has a `dispose` method,
* it will be called when the controller is disposed.
*/
export function useController<T extends new (...args: any) => any>(
controllerClass: T,
...params: ConstructorParams<T>
): InstanceType<T> {
// Create controller instance
const controller = useMemo(() => {
return new controllerClass(...(params as any))
}, params)
// Dispose the controller when the controller changes
useEffect(() => {
return () => {
disposeController(controller)
}
}, [controller])
return controller
}
function disposeController(controller: any) {
if (controller && controller.dispose) {
controller.dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment