React Hooks Simplified: A Complete Beginner's Guide

What do React Hooks do?

Considering this analogy, Imagine one has a toy car. This basic toy cars just roll when you push them , they're simple and straightforward, like react's functional components before 2019. But what if one want this cars with special features like flashing lights, doors that open, or remote control capabilities?

This is where react Hooks comes in, which are simple functions that let one add these special features to any component easily.

React Hooks are simply functions that let you use state and other React features in functional components without writing a class. Introduced in React 16.8, Hooks simplify component logic by allowing you to manage state, handle side effects, and access lifecycle methods seamlessly and directly inside function components, thereby making one development process smoother and more efficient

The Two Most Important Hooks for Beginners

1. useState( ) : Your Component's Memory

The useState function lets your component remember things and update them.

How It Works:

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

This line is saying:

  • Create a memory space called count

  • Start with the value 0 in it

  • Give me a function called setCount that I can use to update this value

import { useState } from "react";

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

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

export default Counter;

Explanation:

  • setCount(count + 1) updates the count state.

  • React detects the change and re-renders the component.

  • The updated count appears on the screen.

2. useEffect( ): Making Things Happen at the Right Time

The useEffect function lets one run code at specific times, like when your component first appears or when certain values change.

How It Works:

useEffect(() => {
  // Code that runs at specific times
}, [dependencies]);

The code inside will run:

  • After the component appears on screen

  • After every update IF you don't provide the second argument

  • Only when values in the dependencies array change

import { useState, useEffect } from "react";

function ProfilePage() {
  const [profile, setProfile] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetch("https://api.example.com/user/123")
      .then(response => response.json())
      .then(data => {
        setProfile(data);
        setIsLoading(false);
      });
  }, []); 

  return (
    <div>
      {isLoading ? (
        <p>Loading your profile...</p>
      ) : (
        <div>
          <h1>Hello, {profile.name}!</h1>
          <p>Email: {profile.email}</p>
        </div>
      )}
    </div>
  );
}

The above fetches a user's profile when their page loads. Let think of useEffect as a way to sync one’s component with the outside world. It's like saying, "When this happens, do that."

Other Important Hooks Explained

While useState and useEffect are the most used hooks, React provides several other hooks that add additional functionality. the rest are as follows

  1. useContext ( ) : Sharing Values Without Passing Props

useContext allows components to consume context values without passing props manually at every level.

const theme = useContext(ThemeContext);ate logic, acting as an alternative to useState.
  1. useRef ( ) : Creating a Persistent Reference

The useRef allows storing values that persist across renders but do not trigger re-renders.

const inputRef = useRef(null);
  1. useMemo ( ) & useCallBack ( ): Performance Optimization

  • useMemo: Caches values to avoid unnecessary recalculations.

  • useCallback: Caches functions to prevent re-creation on every render.

const memoizedValue = useMemo(() => computeExpensiveValue(input), [input]);
const memoizedCallback = useCallback(() => handleClick(id), [id]);

Wrapping it Up

React Hooks simplify state and lifecycle management in functional components. Which among them, useState and useEffect are the most widely used, enabling dynamic updates and handling side effects.

  • useState lets components remember things

  • useEffect lets components do things at the right time

However, React provides many other hooks like useContext, useCallBack & useMemo, and useRef for more advanced functionality. Mastering these hooks improves ones efficiency by making ones components more reusable and applications more maintainable.

0
Subscribe to my newsletter

Read articles from Babalola Taiwo Joseph directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Babalola Taiwo Joseph
Babalola Taiwo Joseph