diff --git a/apps/next/src/app/hooks/ComputedExample.tsx b/apps/next/src/app/hooks/ComputedExample.tsx new file mode 100644 index 00000000..3ae539db --- /dev/null +++ b/apps/next/src/app/hooks/ComputedExample.tsx @@ -0,0 +1,48 @@ +'use client' + +import { useState } from 'react' +import { useCounter } from '@/hooks/useCounter' +import { useComputed } from '@/hooks/useComputed' + +export function ComputedExample() { + const [count, increment] = useCounter(0) + const doubled = useComputed(() => count * 2, [count]) + const [firstName, setFirstName] = useState('John') + const [lastName, setLastName] = useState('Doe') + const fullName = useComputed( + () => `${firstName} ${lastName}`, + [firstName, lastName], + ) + + return ( +
+

Computed

+

Count: {count}

+

Doubled: {doubled}

+
+ +
+
+ + +

Full name: {fullName}

+
+
+ ) +} diff --git a/apps/next/src/app/hooks/page.tsx b/apps/next/src/app/hooks/page.tsx index bdcfb63f..5a237e53 100644 --- a/apps/next/src/app/hooks/page.tsx +++ b/apps/next/src/app/hooks/page.tsx @@ -6,6 +6,7 @@ import { DebounceExample } from './DebounceExample' import { CounterExample } from './CounterExample' import { EventListenerExample } from './EventListenerExample' import { ClickOutsideExample } from './ClickOutsideExample' +import { ComputedExample } from './ComputedExample' export default async function HooksPage() { return ( @@ -18,6 +19,7 @@ export default async function HooksPage() { + diff --git a/apps/next/src/hooks/useComputed.ts b/apps/next/src/hooks/useComputed.ts new file mode 100644 index 00000000..44199dbc --- /dev/null +++ b/apps/next/src/hooks/useComputed.ts @@ -0,0 +1,11 @@ +import { useEffect, useState } from 'react' + +export function useComputed(fn: () => T, deps: unknown[] = []) { + const [value, setValue] = useState(fn()) + + useEffect(() => { + setValue(fn()) + }, deps) + + return value +}