惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cloudbric
Cloudbric
V
Visual Studio Blog
L
LangChain Blog
A
About on SuperTechFans
B
Blog
T
Tenable Blog
罗磊的独立博客
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Palo Alto Networks Blog
U
Unit 42
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
C
Check Point Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
Application and Cybersecurity Blog
Application and Cybersecurity Blog
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
NISL@THU
NISL@THU
Forbes - Security
Forbes - Security
S
Securelist
Security Archives - TechRepublic
Security Archives - TechRepublic
Hugging Face - Blog
Hugging Face - Blog
aimingoo的专栏
aimingoo的专栏
Latest news
Latest news
GbyAI
GbyAI
T
Troy Hunt's Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LINUX DO - 热门话题
V2EX - 技术
V2EX - 技术
小众软件
小众软件
Google DeepMind News
Google DeepMind News
K
Kaspersky official blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
O
OpenAI News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
N
Netflix TechBlog - Medium
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build Reusable Logic with Custom Hooks in React
Kathirvel S · 2026-05-18 · via DEV Community

Welcome back to the “Let’s Master React Hooks Together” series.

So far in this series, we’ve explored several important React Hooks and understood how they help manage state, side effects, performance optimization, references, and more inside React applications.

Now we’ve reached one of the most practical and powerful topics in React development — Custom Hooks.

This is the point where React applications start becoming cleaner, smarter, and more reusable.

As applications grow, developers often notice the same logic repeating in multiple components:

  • Fetching API data
  • Managing forms
  • Handling authentication
  • Tracking screen size
  • Working with local storage
  • Managing counters and timers

Instead of rewriting the same logic again and again, React allows us to extract that logic into reusable functions called Custom Hooks.

In this episode, we’ll deeply understand:

  • What Custom Hooks are
  • The official React definition
  • Why they are important
  • When to use them
  • How to create them
  • Real-world examples
  • Best practices
  • Common mistakes to avoid

Let’s get started.


Custom Hooks in React: Reusing Logic the Smart Way

When building React applications, one thing becomes obvious very quickly: the same logic appears again and again.

You fetch data in multiple components.
You track window size in several places.
You handle form inputs repeatedly.
You manage loading states everywhere.

At first, copying and pasting feels fast. But after a while, your code becomes difficult to maintain.

That’s exactly where Custom Hooks become useful.

Custom Hooks are one of the most powerful patterns in React because they allow you to extract reusable logic into a clean and reusable function.

In this article, we’ll understand:

  • What Custom Hooks are
  • The official React definition
  • Why they exist
  • When to use them
  • How to create them
  • Where they are useful in real projects
  • Best practices and common mistakes
  • Real-world examples

What Is a Custom Hook?

According to the official React documentation:

“A custom Hook is a JavaScript function whose name starts with use and that may call other Hooks.”

At first glance, this definition feels simple. But there’s more behind it.

A Custom Hook is basically:

  • A reusable function
  • That contains React logic
  • And can internally use hooks like useState, useEffect, useContext, etc.

Instead of duplicating logic across components, you move that logic into a reusable hook.


Why Custom Hooks Exist

To understand why Custom Hooks matter, let’s first look at a common problem.

Imagine you have multiple components fetching data from an API.

import { useState, useEffect } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((data) => setUsers(data));
  }, []);

  return (
    <div>
      {users.map((user) => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Now another component needs similar fetching logic.

import { useState, useEffect } from "react";

function Posts() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then((data) => setPosts(data));
  }, []);

  return (
    <div>
      {posts.map((post) => (
        <p key={post.id}>{post.title}</p>
      ))}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Notice something?

The fetching logic is almost identical.

This creates problems:

  • Duplicate code
  • Harder maintenance
  • Repeated bug fixes
  • Larger components
  • Poor readability

Custom Hooks solve this by extracting reusable behavior.


Understanding the Real Purpose of Custom Hooks

A lot of developers think Custom Hooks are only for reducing code duplication.

That’s true — but not the full picture.

The real purpose is:

1. Reusability

Write logic once and use it anywhere.

2. Separation of Concerns

Your component focuses on UI while the hook handles logic.

3. Cleaner Components

Components become smaller and easier to read.

4. Better Maintainability

Updating logic in one place updates it everywhere.

5. Easier Testing

You can test business logic separately from UI.


The Rules of Custom Hooks

Custom Hooks follow the same rules as React Hooks.

Rule 1: The function name must start with use

Correct:

useFetchData()

Enter fullscreen mode Exit fullscreen mode

Wrong:

fetchData()

Enter fullscreen mode Exit fullscreen mode

React relies on this naming convention internally.


Rule 2: Hooks must be called at the top level

Do not call hooks inside:

  • loops
  • conditions
  • nested functions

Wrong:

if (show) {
  useEffect(() => {});
}

Enter fullscreen mode Exit fullscreen mode

Correct:

useEffect(() => {
  if (show) {
    // logic here
  }
}, [show]);

Enter fullscreen mode Exit fullscreen mode


How to Create a Custom Hook

The structure is very simple.

function useSomething() {
  // hook logic

  return something;
}

Enter fullscreen mode Exit fullscreen mode

That’s it.

Now let’s build a real example.


Example 1: Creating a useFetch Hook

Step 1: Create the Hook

import { useEffect, useState } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        setLoading(true);

        const response = await fetch(url);

        if (!response.ok) {
          throw new Error("Failed to fetch data");
        }

        const result = await response.json();

        setData(result);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;

Enter fullscreen mode Exit fullscreen mode


Step 2: Use the Hook

import useFetch from "./useFetch";

function Users() {
  const { data, loading, error } = useFetch(
    "https://jsonplaceholder.typicode.com/users"
  );

  if (loading) return <p>Loading...</p>;

  if (error) return <p>{error}</p>;

  return (
    <div>
      {data.map((user) => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Now the component is much cleaner.

The fetching logic lives in one reusable place.


Example 2: Creating a useCounter Hook

One of the simplest and most common examples of a Custom Hook is a counter.

Instead of managing counter logic separately in every component, we can create a reusable hook.

Step 1: Create the Hook

import { useState } from "react";

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

  const increment = () => {
    setCount((prev) => prev + 1);
  };

  const decrement = () => {
    setCount((prev) => prev - 1);
  };

  const reset = () => {
    setCount(initialValue);
  };

  return {
    count,
    increment,
    decrement,
    reset,
  };
}

export default useCounter;

Enter fullscreen mode Exit fullscreen mode


Step 2: Use the Hook

import useCounter from "./useCounter";

function Counter() {
  const {
    count,
    increment,
    decrement,
    reset,
  } = useCounter(10);

  return (
    <div>
      <h2>{count}</h2>

      <button onClick={increment}>
        Increment
      </button>

      <button onClick={decrement}>
        Decrement
      </button>

      <button onClick={reset}>
        Reset
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Now the counter logic is reusable across multiple components.

You can use the same hook anywhere in your application without rewriting the logic again.


When Should You Create a Custom Hook?

Not every repeated line of code needs a Custom Hook.

A good Custom Hook usually appears when:

You repeat logic across multiple components

Example:

  • API fetching
  • Authentication
  • Form handling
  • Pagination
  • Debouncing
  • Local storage access

Your component becomes too large

If a component contains too much logic, extracting it into hooks improves readability.


Logic is unrelated to UI

UI belongs inside components.

Reusable behavior belongs inside hooks.


Where Custom Hooks Are Commonly Used

Custom Hooks are everywhere in modern React applications.


1. API Requests

useFetch()
useUsers()
useProducts()

Enter fullscreen mode Exit fullscreen mode


2. Authentication

useAuth()

Enter fullscreen mode Exit fullscreen mode


3. Theme Handling

useTheme()

Enter fullscreen mode Exit fullscreen mode


4. Form Management

useForm()

Enter fullscreen mode Exit fullscreen mode


5. Window Resize Detection

useWindowSize()

Enter fullscreen mode Exit fullscreen mode


6. Dark Mode

useDarkMode()

Enter fullscreen mode Exit fullscreen mode


7. Local Storage

useLocalStorage()

Enter fullscreen mode Exit fullscreen mode


Example 3: useLocalStorage Hook

Saving values in local storage is common.

Instead of rewriting the logic everywhere, create a reusable hook.

import { useState } from "react";

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);

    return storedValue
      ? JSON.parse(storedValue)
      : initialValue;
  });

  const saveValue = (newValue) => {
    setValue(newValue);

    localStorage.setItem(
      key,
      JSON.stringify(newValue)
    );
  };

  return [value, saveValue];
}

export default useLocalStorage;

Enter fullscreen mode Exit fullscreen mode

Usage:

function App() {
  const [name, setName] = useLocalStorage(
    "username",
    ""
  );

  return (
    <input
      value={name}
      onChange={(e) => setName(e.target.value)}
    />
  );
}

Enter fullscreen mode Exit fullscreen mode


How Custom Hooks Improve Project Structure

Without hooks, components often become messy.

Example of a bad structure:

components/
 ├── Users.jsx
 ├── Products.jsx
 ├── Dashboard.jsx

Enter fullscreen mode Exit fullscreen mode

Each component contains repeated logic.

With hooks:

src/
 ├── components/
 ├── hooks/
 │    ├── useFetch.js
 │    ├── useAuth.js
 │    ├── useLocalStorage.js

Enter fullscreen mode Exit fullscreen mode

Now logic is centralized and reusable.


Important Difference: Component vs Custom Hook

A lot of developers confuse them.

React Component

  • Returns JSX
  • Handles UI rendering
function Button() {
  return <button>Click</button>;
}

Enter fullscreen mode Exit fullscreen mode


Custom Hook

  • Returns logic/data/functions
  • Does NOT return JSX
function useCounter() {
  return { count, increment };
}

Enter fullscreen mode Exit fullscreen mode


Common Mistakes with Custom Hooks

1. Returning JSX from Hooks

Wrong:

function useModal() {
  return <div>Modal</div>;
}

Enter fullscreen mode Exit fullscreen mode

Hooks should return:

  • state
  • functions
  • values
  • logic

Not UI.


2. Creating Hooks Too Early

Not every logic deserves a hook.

If logic is used only once, keep it inside the component.


3. Massive Hooks

Avoid creating giant hooks that do everything.

Bad:

useDashboardEverything()

Enter fullscreen mode Exit fullscreen mode

Keep hooks focused.


4. Ignoring Dependency Arrays

Hooks using useEffect still require proper dependencies.

Wrong dependencies can create bugs.


Advanced Pattern: Hooks Calling Hooks

One powerful feature is that hooks can use other hooks.

Example:

function useAuth() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    // auth logic
  }, []);

  return user;
}

Enter fullscreen mode Exit fullscreen mode

Another hook can reuse it:

function useAdmin() {
  const user = useAuth();

  return user?.role === "admin";
}

Enter fullscreen mode Exit fullscreen mode

This creates highly modular logic.


Real-World Example

Imagine an e-commerce application.

Without hooks:

  • Every page handles fetching
  • Every component manages loading
  • Authentication logic repeats
  • Cart logic duplicates

With hooks:

useProducts()
useCart()
useAuth()
useOrders()
useWishlist()

Enter fullscreen mode Exit fullscreen mode

Everything becomes organized and reusable.


Are Custom Hooks Required?

No.

React applications can work without them.

But as projects grow, Custom Hooks become one of the best ways to keep code maintainable and scalable.

Most modern React applications use them heavily.


Best Practices for Writing Custom Hooks

Keep One Responsibility

Good:

useFetch()

Enter fullscreen mode Exit fullscreen mode

Bad:

useFetchAndThemeAndAuth()

Enter fullscreen mode Exit fullscreen mode


Use Clear Names

Hook names should describe behavior.

Good:

useWindowSize()
useDarkMode()

Enter fullscreen mode Exit fullscreen mode


Return Useful Data

Hooks should expose only what components need.


Handle Errors Properly

Especially in API hooks.


Avoid Unnecessary Re-renders

Use optimization carefully when needed.


Final Thoughts

Custom Hooks are one of React’s cleanest and most practical features.

They help you:

  • Reuse logic
  • Reduce duplication
  • Keep components clean
  • Improve maintainability
  • Build scalable applications

The best way to understand Custom Hooks is to start noticing repeated logic in your own components.

Whenever you find yourself copying the same state management or effect logic multiple times, that’s usually a sign that a Custom Hook could help.

And once you start using them properly, your React code becomes significantly cleaner, easier to manage, and far more reusable.


Conclusion

That’s it for Episode 9 of the “Let’s Master React Hooks Together” series.

In this episode, we explored one of the most practical concepts in React — Custom Hooks — and understood how they help create reusable, clean, and maintainable applications.

We learned:

  • What Custom Hooks are
  • Why React introduced them
  • How to create them
  • When to use them
  • Real-world use cases
  • Best practices and mistakes to avoid

More importantly, we saw how Custom Hooks help separate logic from UI, making React applications much easier to scale and maintain.

As you continue building React projects, you’ll start noticing repeated patterns everywhere. That’s the perfect opportunity to create your own hooks and make your codebase cleaner and smarter.

In the next episode, we’ll continue exploring more advanced React concepts and patterns to strengthen your React development skills step by step.

See you in the next episode of
“Let’s Master React Hooks Together.”