React Hooks

React introduced Hooks in version 16.8 to allow functional components to manage state and side effects, something that was previously only possible in class components.

🧠 useState Hook:

  • The useState hook allows functional components to add state.

  • Syntax: const [state, setState] = useState(initialValue);

  • Example: A counter component that increments a number when clicked.

javascript
1const Counter = () => { 2 const [count, setCount] = useState(0); 3 return <button onClick={() => setCount(count + 1)}>{count}</button>; 4}

🧠 useEffect Hook:

  • The useEffect hook lets you perform side effects like data fetching, subscribing to events, and manual DOM manipulation.

  • Syntax: useEffect(() => { /* effect */ }, [dependencies]);

  • Example: Fetching data when a component mounts.

javascript
1useEffect(() => { 2 fetchData(); 3}, []);

🧠 useMemo Hook:

  • The useMemo hook is used to memoize values, which helps optimize performance by preventing unnecessary re-calculations of expensive calculations.

  • Syntax: const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

In short:

  • useState is used to manage state.
  • useEffect handles side effects in a component.
  • useMemo helps with performance optimization by memoizing values.