React Hooks Objectives

Learning Goals

By the end of this material, you will be able to:

Understanding useState

The useState hook is used to manage state within a functional component:


import { useState } from 'react';

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

  return (
    

Count: {count}

); }

Understanding useEffect

The useEffect hook runs code in response to component lifecycle events:


import { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    return () => clearInterval(interval); // Cleanup on unmount
  }, []);

  return 

Seconds elapsed: {seconds}

; }

Triggers for Re-renders

A React component can re-render when:

Performance Optimization

useCallback and useRef can optimize performance:

Using useCallback


import { useCallback, useState } from 'react';

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

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return ;
}
    

Using useRef


import { useRef } from 'react';

function InputFocus() {
  const inputRef = useRef(null);

  return (
    
); }

Debugging Re-renders

Use React Developer Tools to inspect component re-renders. The React.memo higher-order component can help prevent unnecessary renders.

Conclusion

React Hooks allow functional components to manage state, handle side effects, and optimize performance. Mastering hooks is essential for modern React development.