Master the essential React Hooks for functional components
Managing component state
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'}
);
};
Managing side effects in components
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 */};
};
Accessing DOM elements and persisting values
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
);
};
Creating reusable hooks logic
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}
);
};