You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数组件中定义State的最佳实践:两种写法对比

React useState Typing: Which Syntax is Better?

Great question! Let’s unpack these two TypeScript approaches for typing your React component’s state and clarify why one is far better suited for most cases.

First Approach: Explicit Array Type Annotation

export function TestComponent() {
  const [state, setState]: [string, Function] = React.useState('');
}

While this technically works, it has a critical downside: the Function type for setState is way too vague. React’s setState isn’t just any function—it’s a specific utility that accepts either the new state value or a callback function that takes the previous state and returns the updated state. By using Function, you lose all TypeScript type checking for setState’s arguments. For example, you could accidentally pass a number to setState and TypeScript wouldn’t flag it, even though that would cause unexpected behavior in your component.

Second Approach: Generic Type Argument

export function TestComponent() {
  const [state, setState] = React.useState<string>('');
}

This is the optimal choice—and your instinct to prefer it because it’s cleaner is totally correct! Here’s why it’s the better option:

  • Precise, automatic typing for setState: When you use the generic useState<string>, TypeScript automatically infers the exact type for setState (it’ll be (value: string | ((prevState: string) => string)) => void). This means you get full type safety: if you try to pass a non-string value to setState, TypeScript will throw an error immediately, catching bugs early in your workflow.
  • Conciseness: You don’t have to manually type out the entire array structure—React’s built-in useState generic handles all that heavy lifting for you.
  • Flexibility for complex state: This syntax really shines when working with more complex state types (like unions, custom interfaces, or nullable values). For example, if your state could be a string or null, you’d write useState<string | null>(null)—far cleaner than writing out the full array type with all possible state and setState argument variations.

Final Verdict

Stick with the generic useState<string>('') syntax. It’s not just more concise—it provides better type safety and aligns with React and TypeScript’s recommended best practices.

内容的提问来源于stack exchange,提问作者D.Bronder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:02:39