feat(chapter3): add useRef demo

Demonstrate retaining the previous counter value with a ref while updating state through a shadcn button.
This commit is contained in:
jiawei
2026-08-30 17:25:30 +08:00
parent 4823d13938
commit efe03af847
+31
View File
@@ -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 (
<div className={clsx($styles.container, 'w-80')}>
<h2 className="text-center">useRef Demo</h2>
<p className="py-5 text-center">{count}</p>
<div className="flex justify-around">
<Button onClick={() => setCount(Math.ceil(Math.random() * 10))} variant="outline">
</Button>
</div>
</div>
);
};
export default RefDemo;