React Hooks

Hooks are special functions that let you “hook into” React features like state and lifecycle from function components.

Introduced in React 16.8, hooks make class components largely unnecessary.

1. useState

Used to declare and manage local state inside a function component.

const [count, setCount] = useState(0);

Syntax:

const [stateVariable, setStateFunction] = useState(initialValue);

2. useEffect

Used for side effects: data fetching, subscriptions, timers, DOM manipulation.

useEffect(() => {
  console.log("Component mounted or updated");
}, [dependency]);

Syntax:

useEffect(callback, [dependencies]);

Cleanup:

useEffect(() => {
  const timer = setInterval(...);
  return () => clearInterval(timer);
}, []);

3. useContext

Allows components to consume data from Context without prop drilling.

const user = useContext(UserContext);

4. useRef

Used to reference DOM elements or persist values without triggering re-renders.

const inputRef = useRef(null);
<input ref={inputRef} />

5. useMemo

Memoizes the result of an expensive computation to avoid unnecessary recalculations.

const result = useMemo(() => computeExpensiveValue(a, b), [a, b]);

6. useCallback

Memoizes a function to prevent unnecessary re-creations across renders.

const handleClick = useCallback(() => {
  doSomething();
}, [dependency]);

7. useReducer (Alternative to useState)

Used for more complex state logic, similar to Redux-style reducers.

const [state, dispatch] = useReducer(reducer, initialState);

8. Custom Hooks

A custom hook is a function that uses other hooks. It must start with use.

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return width;
}

Summary of Common Hooks

HookUsed for
useStateSimple local state
useEffectSide effects, data fetching
useContextContext data access
useRefDOM refs, persistent value
useMemoMemoize calculation
useCallbackMemoize functions
useReducerComplex state logic
Custom hooksReusable logic

Bình luận

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *