React Hooks 的优势和使用场景

70 阅读2分钟
# React Hooks 的优势和使用场景

## 1. React Hooks 的优势

### 1.1 简化组件逻辑
Hooks 允许在不编写 class 的情况下使用 state 和其他 React 特性,使得函数组件也能拥有状态和生命周期能力。这显著简化了组件逻辑,减少了样板代码。

```jsx
// Class 组件
class Counter extends React.Component {
  state = { count: 0 };
  
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

// 使用 Hooks 的函数组件
function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

1.2 更好的代码复用

通过自定义 Hook,可以轻松地在多个组件之间复用状态逻辑,避免了高阶组件和渲染属性带来的嵌套问题。

// 自定义 Hook
function useCounter(initialValue) {
  const [count, setCount] = useState(initialValue);

  const increment = () => {
    setCount(count + 1);
  };

  return { count, increment };
}

// 使用自定义 Hook
function CounterA() {
  const { count, increment } = useCounter(0);
  return <button onClick={increment}>Count A: {count}</button>;
}

function CounterB() {
  const { count, increment } = useCounter(10);
  return <button onClick={increment}>Count B: {count}</button>;
}

1.3 更清晰的副作用管理

useEffect 将生命周期方法(如 componentDidMountcomponentDidUpdatecomponentWillUnmount)统一为一个 API,使得副作用管理更加直观。

function DataFetcher({ url }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(url);
      const result = await response.json();
      setData(result);
    };

    fetchData();
  }, [url]); // 依赖项数组确保只在 url 变化时重新获取数据

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}

1.4 更细粒度的状态管理

Hooks 允许将状态逻辑拆分为多个独立的 useStateuseReducer,使得状态管理更加模块化和可维护。

function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  return (
    <form>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Name"
      />
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
    </form>
  );
}

2. React Hooks 的使用场景

2.1 状态管理

useStateuseReducer 适用于管理组件的局部状态,尤其是当状态逻辑较为复杂时。

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const addTodo = () => {
    if (inputValue.trim()) {
      setTodos([...todos, inputValue]);
      setInputValue('');
    }
  };

  return (
    <div>
      <input
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button onClick={addTodo}>Add Todo</button>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
    </div>
  );
}

2.2 副作用处理

useEffect 适用于处理数据获取、订阅、手动 DOM 操作等副作用。

function WindowSizeTracker() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() =>