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:
@@ -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;
|
||||
Reference in New Issue
Block a user