DEV Community

Huzaifa shoaib
Huzaifa shoaib

Posted on

πŸš€ Understanding React Hooks in Depth

β€œThe best way to understand something is to break it down to its simplest form.”

React Hooks were introduced in React 16.8, changing how we write components forever. They allow you to use state and lifecycle features without writing a class. Let’s explore them in a beginner-friendly, practical way.

🧠 Why Hooks?

Before Hooks, you had to use class components to manage state and side effects. With Hooks, functional components became just as powerful β€” and a lot cleaner.

β€œSimplicity does not precede complexity, but follows it.” β€” Alan Perlis

πŸ”§ Commonly Used Hooks

1. useState() β€” State in Functional Components

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

It returns a stateful value and a function to update it.

2. useEffect() β€” Side Effects (e.g., API calls, DOM updates)

useEffect(() => {
  console.log("Component mounted or updated");
}, [dependency]);

Think of it as componentDidMount, componentDidUpdate, and componentWillUnmount in one.

3. useContext() β€” Access Global Data (without prop drilling)

const theme = useContext(ThemeContext);

It helps you consume values from React Context easily.

4. useRef() β€” Mutable Values That Persist

const inputRef = useRef(null);

It’s useful for accessing DOM nodes or keeping mutable variables that don’t trigger re-renders.

5. useReducer() β€” Advanced State Management

const [state, dispatch] = useReducer(reducer, initialState);

Great for complex state logic, often used with global state tools.

🎯 Custom Hooks β€” Reusable Logic

You can build your own hooks to reuse 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;
}

β€œDon’t Repeat Yourself β€” make a custom hook instead.” β€” Every React Dev

βœ… Final Thoughts

React Hooks make code cleaner, reusable, and easier to reason about.

Once you master them, your productivity as a React developer skyrockets πŸš€

β€œHooks are not magic. They’re just functions β€” but really powerful ones.”

Top comments (0)