I switch between Angular and React projects, and I like the concepts of “React Hooks.”
With signal() and effect(), I can now implement “React Hooks” in Angular. However, I am not sure if this is the Angular way to use signals/effects.
Any opinions? Any concerns?
Example:
import { effect, signal } from "@angular/core";
export function useTimer(seconds: number) {
const timer = signal(seconds)
let timeoutHandler: number | undefined;
const decrease = () => {
timeoutHandler = window.setTimeout(() => {
timer.set(timer() - 1);
if (timer() > 0) {
decrease();
}
}, 1000)
}
effect((onCleanup) => {
decrease();
onCleanup(() => {
() => window.clearTimeout(timeoutHandler);
})
}, {allowSignalWrites: true});
return timer;
}
Ussage:
export class SomeComponent {
timer= useTimer(10)