# React19
# 从零开始
npm create vite@latest my-app -- --template react
# reactrouter
# framework mode 框架模式
# hooks 核心api
# useState 状态管理
const [count, setCount] = useState(0);
setCount(count + 1);
# useEffect 挂载&卸载&监听
useEffect(() => {
console.log("组件渲染");
return () => console.log("组件卸载");
}, []);
# useRef 获取dom
const inputRef = useRef<HTMLInputElement>(null);
<input ref={inputRef} />;
# useMemo 避免不必要的计算
const double = useMemo(() => count * 2, [count]);
# useCallback 缓存
const handleClick = useCallback(() => alert("Clicked"), []);
# *useContext 跨组件通信
const ThemeContext = createContext("light");
const theme = useContext(ThemeContext);
# useReducer 处理复杂状态
const reducer = (state, action) => {
if (action.type === "increment") return state + 1;
return state;
};
const [count, dispatch] = useReducer(reducer, 0);
dispatch({ type: "increment" });
# useLayoutEffect 比useEffect先执行
useLayoutEffect(() => {
console.log("DOM 更新后");
}, []);
# forwardRef 让父组件获取子组件的ref
const Input = forwardRef((props, ref) => <input ref={ref} {...props} />);
# useParams 获取动态路由参数
const { id } = useParams();