React Hooks: Modern State Management in Functional Components

React Hooks let you use state and other features in functional components. They simplify code and promote reusable logic.

## useState

```jsx
function Counter() {
 const [count, setCount] = useState(0);
 return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
```

## useEffect

```jsx
function UserProfile({ userId }) {
 const [user, setUser] = useState(null);

 useEffect(() => {
   fetch(`/api/users/${userId}`)
     .then(res => res.json())
     .then(setUser);
 }, [userId]);

 return <div>{user?.name}</div>;
}
```

## useRef

```jsx
function TextInput() {
 const inputRef = useRef(null);
 const focus = () => inputRef.current.focus();
 return <input ref={inputRef} />;
}
```

## useContext

```jsx
const ThemeContext = createContext('light');

function ThemedButton() {
 const theme = useContext(ThemeContext);
 return <button className={theme}>Click me</button>;
}
```

## Custom Hooks

```jsx
function useLocalStorage(key, initialValue) {
 const [value, setValue] = useState(() => {
   const stored = localStorage.getItem(key);
   return stored ? JSON.parse(stored) : initialValue;
 });

 useEffect(() => {
   localStorage.setItem(key, JSON.stringify(value));
 }, [key, value]);

 return [value, setValue];
}
```

## useReducer

```jsx
function reducer(state, action) {
 switch (action.type) {
   case 'increment': return { count: state.count + 1 };
   case 'decrement': return { count: state.count - 1 };
 }
}

const [state, dispatch] = useReducer(reducer, { count: 0 });
```

## Rules

1. Only call hooks at the top level
2. Only call hooks from React functions
3. Wrap effects with proper dependencies

## Conclusion

Hooks replaced class components for most use cases. Master useState and useEffect first, then explore custom hooks for reusability.

评论
暂无评论