# Mastering React Hooks
React hooks revolutionize how we write React components. Here are the essential hooks every developer should master:
import React, { useState, useEffect } from 'react';
// useState for managing component statefunction Counter() { const [count, setCount] = useState(0); const [name, setName] = useState('');
// Object state const [user, setUser] = useState({ name: '', email: '' });
const updateUser = (field, value) => { setUser(prev => ({ ...prev, [field]: value })); };
return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}> Increment </button> <button onClick={() => setCount(prev => prev - 1)}> Decrement </button>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter name" /> </div> );}
useEffect for side effects and lifecycle management:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
// Effect with cleanup useEffect(() => { let cancelled = false;
const fetchUser = async () => { try { setLoading(true); const response = await fetch(`/api/users/${userId}`); const userData = await response.json();
if (!cancelled) { setUser(userData); setError(null); } } catch (err) { if (!cancelled) { setError(err.message); } } finally { if (!cancelled) { setLoading(false); } } };
fetchUser();
// Cleanup function return () => { cancelled = true; }; }, [userId]); // Dependency array
// Effect for document title useEffect(() => { if (user) { document.title = `Profile: ${user.name}`; }
return () => { document.title = 'My App'; }; }, [user]);
if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!user) return <div>User not found</div>;
return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> );}
Custom hooks for reusable logic:
import { useState, useEffect } from 'react';
// Custom hook for API data fetchingfunction useApi(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
useEffect(() => { const fetchData = async () => { try { setLoading(true); const response = await fetch(url); const result = await response.json(); setData(result); setError(null); } catch (err) { setError(err.message); } finally { setLoading(false); } };
if (url) { fetchData(); } }, [url]);
return { data, loading, error };}
// Custom hook for local storagefunction useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error('Error reading from localStorage:', error); return initialValue; } });
const setValue = (value) => { try { setStoredValue(value); window.localStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.error('Error saving to localStorage:', error); } };
return [storedValue, setValue];}
// Using custom hooksfunction TodoApp() { const [todos, setTodos] = useLocalStorage('todos', []); const { data: users, loading } = useApi('/api/users');
const addTodo = (text) => { const newTodo = { id: Date.now(), text, completed: false }; setTodos(prev => [...prev, newTodo]); };
return ( <div> <h1>Todo App</h1> {/* Todo implementation */} </div> );}
# Create new React appnpx create-react-app my-react-appcd my-react-app
# Start development servernpm start
# Build for productionnpm run build