Mastering React Hooks: A Practical Tutorial for Beginners

React Hooks let you use state and lifecycle features in functional components without writing a class. They simplify your code and make logic reusable. This tutorial covers the most essential hooks to get you started quickly.

1. Using useState for Local State

The useState hook returns an array with the current state and a function to update it. Call it at the top of your component:

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

To update, call setCount(newValue). React re-renders the component automatically. You can use multiple useState calls for different state values.

Article illustration

2. Managing Side Effects with useEffect

useEffect runs code after render, ideal for data fetching, subscriptions, or DOM updates. Pass a function and an optional dependency array:

useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);

Without dependencies, it runs every render. With an empty array [], it runs only on mount. Return a cleanup function to avoid memory leaks.

3. Sharing Logic with Custom Hooks

Extract reusable logic into a custom hook. Name it starting with use. Example: a hook to track window width:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return width;
}

Now any component can call const width = useWindowWidth(). Custom hooks keep your components clean and focused.

4. Following the Rules of Hooks

Always call hooks at the top level of your component, never inside loops, conditions, or nested functions. Only call hooks from React functions (components or custom hooks). This ensures consistent state management.

React Hooks make your code more predictable and easier to test. Start with useState and useEffect, then create custom hooks to eliminate duplication. Practice these patterns to become proficient quickly.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *