Hooks
Hooks allow you to use state and other React features in function components.
useState
Section titled “useState”Manage component state.
import { useState } from 'react';
function Counter() { const [count, setCount] = useState(0);
return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> );}useEffect
Section titled “useEffect”Handle side effects.
import { useEffect, useState } from 'react';
function Example() { const [data, setData] = useState(null);
useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(data => setData(data)); }, []); // Empty dependency array means execute only once
return <div>{data}</div>;}useContext
Section titled “useContext”Access React context.
import { useContext } from 'react';import { ThemeContext } from './ThemeContext';
function ThemedButton() { const theme = useContext(ThemeContext); return <button style={{ background: theme }}>Themed Button</button>;}useRef
Section titled “useRef”Get DOM references.
import { useRef } from 'react';
function TextInput() { const inputRef = useRef(null);
const focusInput = () => { inputRef.current.focus(); };
return ( <> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </> );}Common Hooks
Section titled “Common Hooks”| Hook | Purpose |
|---|---|
| useState | Manage component state |
| useEffect | Handle side effects |
| useContext | Access context data |
| useRef | Get DOM references |
| useMemo | Cache computation results |
| useCallback | Cache functions |