Getting Started with React Hooks

Getting Started with React Hooks

React Hooks have revolutionized how we write functional components. Let’s explore the fundamentals and best practices.

What are Hooks?

Hooks are functions that let you “hook into” React features. They don’t work inside classes, but they let you use React without writing a class.

The useState Hook

The useState hook is one of the most commonly used hooks. Here’s how to use it:

import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

The useEffect Hook

useEffect lets you perform side effects in functional components:

import { useEffect, useState } from 'react';

function UserProfile({ userId }: { userId: number }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      setLoading(true);
      const response = await fetch(`/api/users/${userId}`);
      const data = await response.json();
      setUser(data);
      setLoading(false);
    };

    fetchUser();
  }, [userId]);

  if (loading) return <div>Loading...</div>;
  if (!user) return <div>No user found</div>;

  return <div>{user.name}</div>;
}

Best Practices

  1. Only call hooks at the top level - Don’t call hooks inside loops, conditions, or nested functions
  2. Only call hooks from React function components - Don’t call them from regular JavaScript functions
  3. Use the ESLint plugin - The eslint-plugin-react-hooks plugin helps enforce these rules

Custom Hooks

You can create your own hooks to share stateful logic between components:

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;
}

function MyComponent() {
  const width = useWindowWidth();
  return <div>Window width: {width}px</div>;
}

Hooks provide a cleaner and more intuitive way to work with React. Master them, and you’ll write better, more reusable components!