Back to all posts
Programming

A Beginner's Guide to React Hooks

By HTG

React Hooks, introduced in React 16.8, revolutionized how developers write components. They allow you to use state and other React features in functional components, eliminating the need for cumbersome class components. If you're new to Hooks, this guide will introduce you to the most essential ones.

What Are React Hooks?

Hooks are functions that let you "hook into" React state and lifecycle features from function components. They are simpler, more reusable, and lead to more readable code.

1. useState

The useState Hook is the most fundamental Hook. It allows you to add state to your functional components.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useState(0) initializes a state variable called count to 0. setCount is the function used to update this state.

2. useEffect

The useEffect Hook lets you perform side effects in your components. Common side effects include fetching data, setting up a subscription, or manually changing the DOM. It runs after every render by default, but you can control when it runs.

import React, { useState, useEffect } from 'react';

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const timerId = setInterval(() => {
      setTime(prevTime => prevTime + 1);
    }, 1000);

    // Cleanup function
    return () => clearInterval(timerId);
  }, []); // The empty array [] means this effect runs only once on mount

  return <p>Timer: {time} seconds</p>;
}

The cleanup function returned by useEffect is crucial for preventing memory leaks, such as when a component unmounts.

3. useContext

The useContext Hook provides a way to pass data through the component tree without having to pass props down manually at every level. It's perfect for managing global state like themes or user authentication.

Rules of Hooks

  1. Only Call Hooks at the Top Level: Don't call Hooks inside loops, conditions, or nested functions.
  2. Only Call Hooks from React Functions: Call them from React functional components, not regular JavaScript functions.

By mastering useState and useEffect, you'll be well on your way to writing modern, efficient, and elegant React applications.


You Might Also Like


Related Posts

Programming
The Art of Debugging: A Developer's Guide to Finding and Fixing Bugs
Debugging is a critical skill for any developer. Learn effective strategies and tools to identify and resolve bugs in your code efficiently, turning frustration into a learning opportunity.

By HTG

Read More
Programming
Free Online Tools Every Student and Developer Should Know in 2025
A curated list of 10 essential and free online tools for students and developers in 2025, from the GitHub Student Developer Pack to Google Colab. Boost your productivity without spending a dime.

By Huzi

Read More
Programming
A Beginner's Guide to Learning ReactJS
Kickstart your web development journey with this comprehensive introduction to ReactJS, the most popular JavaScript library.

By HTG

Read More
Programming
Mastering Python Decorators: A Practical Guide
Unlock the power of Python decorators to write cleaner, more efficient, and more maintainable code.

By HTG

Read More
Programming
Getting Started with Python for Absolute Beginners
Python is one of the most popular and versatile programming languages. This introductory guide will walk you through setting up your environment and writing your first lines of code.

By HTG

Read More
Programming
Demystifying REST APIs: A Beginner's Guide
What exactly is a REST API? This guide breaks down the core concepts of Representational State Transfer, including resources, HTTP verbs, and status codes, in a simple and easy-to-understand way.

By Huzi

Read More
Technology
Xiaomi 15 Pro vs Infinix Zero Ultra 5G — What You Gain & What You Lose
Two phones, two worlds: the Xiaomi 15 Pro sits high in the flagship realm, while the Infinix Zero Ultra 5G is more of a high-spec mid-range. We compare them by spec, performance, camera, battery, price, and see which weaknesses or strengths each brings — in Pakistan’s context.

By Huzi

Read More
Linux
Fix: Wi-Fi Not Working After Arch Linux Installation (2025 Guide)
A step-by-step guide to fix Wi-Fi issues after an Arch Linux installation. Learn how to enable NetworkManager, install wireless drivers and firmware for Intel, Broadcom, and Realtek, and diagnose adapter issues.

By Huzi

Read More
Education
University Admission Guide in Pakistan: 2025 Updates
In 2025, your dream degree is 4 clicks away—if you dodge the deadline potholes. This guide covers top universities, HEC scholarships & digital application hacks.

By Huzi

Read More
Business
The Rise of Pakistani Women in Business
From tech innovators like Sehat Kahani to creative entrepreneurs, Pakistani women are reshaping the business landscape. A look at the stories, challenges, and triumphs of female founders in 2025.

By Huzi

Read More
Linux
Best Arch Linux Desktop Environments: KDE vs XFCE vs GNOME (2025)
An in-depth comparison of KDE Plasma, XFCE, and GNOME for Arch Linux in 2025. See performance benchmarks, RAM/CPU usage, and find the best DE for your hardware and workflow.

By Huzi

Read More