From efe03af8475aec364d40efaa4f40d76e121d33f7 Mon Sep 17 00:00:00 2001 From: jiawei Date: Sun, 30 Aug 2026 17:25:30 +0800 Subject: [PATCH] feat(chapter3): add useRef demo Demonstrate retaining the previous counter value with a ref while updating state through a shadcn button. --- chapter3/src/app/demo/_components/ref.tsx | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 chapter3/src/app/demo/_components/ref.tsx diff --git a/chapter3/src/app/demo/_components/ref.tsx b/chapter3/src/app/demo/_components/ref.tsx new file mode 100644 index 0000000..0650011 --- /dev/null +++ b/chapter3/src/app/demo/_components/ref.tsx @@ -0,0 +1,31 @@ +// src/app/demo/_components/ref.tsx +'use client'; + +import { type FC, useEffect, useState, useRef } from 'react'; +import { Button } from '@/app/_components/shadcn/ui/button'; +import clsx from 'clsx'; +import $styles from './style.module.css'; + +const RefDemo: FC = () => { + const [count, setCount] = useState(0); + const inited = useRef(count); + useEffect(() => { + if (inited.current !== count) { + inited.current = count; + console.log('changed'); + } + }, [count]); + return ( +
+

useRef Demo

+

{count}

+
+ +
+
+ ); +}; + +export default RefDemo;