Getting Started with React Hooks: A Complete Guide
React Hooks arrived in React 16.8 and changed how we write components. Instead of class components for state and lifecycle logic, you can use functions with useState, useEffect, and more.
Why Hooks Matter
Hooks let you reuse stateful logic without higher-order components or render props. They keep related logic together-fetching data, subscribing to events, and updating the DOM live in one place instead of spread across lifecycle methods.
useState and useEffect
useState declares local state in a function component. useEffect runs side effects after render-API calls, subscriptions, or DOM updates.
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let cancelled = false;
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => { if (!cancelled) setUser(data); });
return () => { cancelled = true; };
}, [userId]);
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
Rules of Hooks
Call Hooks only at the top level of React functions-never inside loops, conditions, or nested functions. Custom Hooks (functions whose names start with use) let you extract and share logic across components.
Conclusion
Hooks are the default way to build React apps in 2020 and beyond. Start with useState and useEffect, then explore useContext, useReducer, and useMemo as your apps grow in complexity.