React Example

React Hooks

Master the essential React Hooks for functional components

useState Hook

Managing component state

Basic useState Example

import { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  const [isActive, setIsActive] = useState(false);

  const increment = () => {
    setCount(prevCount => prevCount + 1);
    setIsActive(true);
  };

  return (
    

Count: {count}

Status: {isActive ? 'Active' : 'Inactive'}

); };

Key Points

  • Initialize state with useState(initialValue)
  • Use functional updates for state that depends on previous value
  • State updates are asynchronous
  • Each state variable should be atomic

useEffect Hook

Managing side effects in components

useEffect Examples

import { useEffect, useState } from 'react';

const DataFetcher = ({ userId }) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(`/api/user/${userId}`);
        const result = await response.json();
        setData(result);
      } catch (error) {
        console.error('Error:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    // Cleanup function
    return () => {
      // Cancel any pending requests
      // Reset state if needed
    };
  }, [userId]); // Only re-run when userId changes

  if (loading) return 
Loading...
; if (!data) return
No data found
; return
{/* Render data */}
; };

Key Points

  • Effects run after every render
  • Use dependency array to control when effects run
  • Clean up with return function
  • Handle async operations properly

useRef Hook

Accessing DOM elements and persisting values

useRef Example

import { useRef, useEffect } from 'react';

const AutoFocusInput = () => {
  const inputRef = useRef(null);
  const renderCount = useRef(0);

  useEffect(() => {
    // Focus input on mount
    inputRef.current?.focus();

    // Track render count
    renderCount.current += 1;
  }, []);

  return (
    

Component has rendered {renderCount.current} times

); };

Key Points

  • Access DOM elements directly
  • Persist values between renders
  • Changes don't trigger re-renders
  • Useful for storing previous values

Custom Hooks

Creating reusable hooks logic

Custom Hook Example

import { useState, useEffect } from 'react';

// Custom hook for handling API requests
const useApi = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
        setError(null);
      } catch (err) {
        setError(err.message);
        setData(null);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
};

// Using the custom hook
const UserProfile = ({ userId }) => {
  const { data, loading, error } = useApi(`/api/users/${userId}`);

  if (loading) return 
Loading...
; if (error) return
Error: {error}
; if (!data) return
No data found
; return (

{data.name}

{data.email}

); };

Key Points

  • Start hook names with 'use'
  • Compose multiple hooks together
  • Follow hooks rules
  • Keep hooks focused and reusable