Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Custom Hooks — Encapsulating Reusable Logic

Custom Hooks — Encapsulating Reusable Logic

In this chapter you will learn React best practices - using custom Hooks to encapsulate reusable logic, making components cleaner and easier to maintain.


What Is a Custom Hook?

As features grow, useState and useEffect become scattered across components, with duplicate logic between different components.

A custom Hook extracts the combined logic of multiple Hooks into a function whose name starts with 'use'.

Its essence: an ordinary JS function that uses React Hooks internally.


Why Do We Need Custom Hooks?

Without Custom Hooks With Custom Hooks
Each component writes its own fetch + filter logic One usePosts() reused everywhere
Data logic and UI logic are mixed together Data logic is independent; components only care about the UI
Changing one piece of logic requires editing multiple files Change one place, all components update in sync
Components easily reach 200+ lines Components are typically < 80 lines

Naming Conventions and Hook Rules

Convention Description Example
Starts with use React uses this to identify Hooks and apply lint rules usePosts、useDarkMode
Placed in the hooks/ directory Easy to find and maintain src/hooks/usePosts.js
Can only be called at the top level of function components Cannot be called in conditions/loops/nested functions —
Return data or methods Let the caller access the state and logic inside the Hook return { data, isLoading }

Hook usage rules: 1. Only call Hooks at the top level of function components; 2. Only call Hooks in React functions (function components or custom Hooks). This ensures the call order of Hooks is consistent on every render.


usePosts — Encapsulating Article Data Logic

Example

// File path: src/hooks/usePosts.js

import

{

useState

,

useEffect

,

useMemo

}

from

'react'

export

function

usePosts

(

)

{

 

const

[

articles

,

setArticles

]

=

useState

(

[

]

)

 

const

[

isLoading

,

setIsLoading

]

=

useState

(

true

)

 

const

[

error

,

setError

]

=

useState

(

null

)

 

const

[

activeCategory

,

setActiveCategory

]

=

useState

(

'All'

)

 

const

[

keyword

,

setKeyword

]

=

useState

(

''

)

 

// Load data

  useEffect

(

(

)

=>

{

    let cancelled

=

false

    async

function

fetchPosts

(

)

{

      setIsLoading

(

true

)

      setError

(

null

)

     

try

{

       

const

res

=

await fetch

(

'/posts.json'

)

       

if

(

!

res.

ok

)

throw

new

Error

(

`HTTP $

{

res.

status

}

`

)

       

const

data

=

await res.

json

(

)

       

if

(

!

cancelled

)

setArticles

(

data

)

     

}

catch

(

err

)

{

       

if

(

!

cancelled

)

setError

(

err.

message

)

     

}

finally

{

       

if

(

!

cancelled

)

setIsLoading

(

false

)

     

}

   

}

    fetchPosts

(

)

   

return

(

)

=>

{

cancelled

=

true

}

 

}

,

[

]

)

 

// Extract all categories

 

const

categories

=

useMemo

(

(

)

=>

{

   

return

[

'All'

,

...

new

Set

(

articles.

map

(

a

=>

a.

category

)

)

]

 

}

,

[

articles

]

)

 

// Filter by category + keyword

 

const

filteredArticles

=

useMemo

(

(

)

=>

{

    let result

=

articles

   

if

(

activeCategory

!==

'All'

)

{

      result

=

result.

filter

(

a

=>

a.

category

===

activeCategory

)

   

}

   

if

(

keyword.

trim

(

)

)

{

     

const

kw

=

keyword.

trim

(

)

.

toLowerCase

(

)

      result

=

result.

filter

(

a

=>

        a.

title

.

toLowerCase

(

)

.

includes

(

kw

)

||

        a.

summary

.

toLowerCase

(

)

.

includes

(

kw

)

     

)

   

}

   

return

result

 

}

,

[

articles

,

activeCategory

,

keyword

]

)

 

// Find an article by ID

 

function

getArticleById

(

id

)

{

   

return

articles.

find

(

a

=>

a.

id

===

Number

(

id

)

)

 

}

 

// Reload

 

function

refetch

(

)

{

   

// Another way to trigger useEffect: use a key or augment state

    window.

location

.

reload

(

)

 

}

 

return

{

    articles

,

isLoading

,

error

,

    activeCategory

,

setActiveCategory

,

    keyword

,

setKeyword

,

    categories

,

    filteredArticles

,

    getArticleById

,

    refetch

 

}

}

The Home Page Using usePosts

Example

// File path: src/pages/HomePage.jsx

import

{

usePosts

}

from

'../hooks/usePosts'

import

BlogCard from

'../components/BlogCard'

import

CategoryFilter from

'../components/CategoryFilter'

function

HomePage

(

)

{

 

// Get all article-related data and operations in one line

 

const

{

    isLoading

,

error

,

    activeCategory

,

setActiveCategory

,

    keyword

,

setKeyword

,

    categories

,

    filteredArticles

,

    refetch

 

}

=

usePosts

(

)

 

if

(

isLoading

)

return

<

p className

=

"status-msg"

Loading...

p

 

if

(

error

)

return

(

   

<

div className

=

"status-msg error"

     

<

p

Loading failed:

{

error

}

p

     

<

button onClick

=

{

refetch

}

Retry

button

   

div

 

)

 

return

(

   

<

div

<

h2 className

=

"section-title"

Latest Articles

h2

     

<

div className

=

"search-bar"

       

<input type="text" value={keyword}onChange={e=>setKeyword(>

e.

target

.

value

)

}

          placeholder

=

"Search article title or abstract..."

          className

=

"search-input"

       

/>

       

{

keyword

&&

<

span className

=

"clear-btn"

onClick

=

{

(

)

=>

setKeyword

(

''

)

}

✕

span

}

     

div

     

<

CategoryFilter

categories

=

{

categories

}

activeCategory

=

{

activeCategory

}

onCategoryChange

=

{

setActiveCategory

}

/>

<

p className

=

"result-info"

Total

{

filteredArticles.

length

}

articles

p

     

{

filteredArticles.

length

===

0

?

(

       

<

p className

=

"empty-tip"

No matching articles

p

     

)

:

(

       

<

div className

=

"article-grid"

         

{

filteredArticles.

map

(

article

=>

(

           

<

BlogCard key

=

{

article.

id

}

{

...

article

}

/>

         

)

)

}

       

div

     

)

}

   

div

 

)

}

export

default

HomePage

The Detail Page Using usePosts

Example

// File path: src/pages/PostPage.jsx

import

{

useParams

,

Link

}

from

'react-router-dom'

import

{

usePosts

}

from

'../hooks/usePosts'

function

PostPage

(

)

{

 

const

{

id

}

=

useParams

(

)

 

const

{

isLoading

,

error

,

getArticleById

}

=

usePosts

(

)

 

const

article

=

getArticleById

(

id

)

 

if

(

isLoading

)

return

<

p className

=

"status-msg"

Loading...

p

 

if

(

error

)

return

<

p className

=

"status-msg error"

Loading failed:

{

error

}

p

 

if

(

!

article

)

{

   

return

(

     

<

div className

=

"not-found"

       

<

h2

Article does not exist

h2

       

<

Link to

=

"/"

Back to Home

Link

     

div

   

)

 

}

 

return

(

   

<

article className

=

"post-view"

     

<

span className

=

"category-tag"

{

article.

category

}

span

     

<

h1

{

article.

title

}

h1

     

<

time

{

article.

date

}

time

     

<

div className

=

"content"

dangerouslySetInnerHTML

=

{

{

__html

:

article.

content

}

}

/>

     

<

Link to

=

"/"

className

=

"back-link"

← Back to Home

Link

   

article

 

)

}

export

default

PostPage

Note: If a user directly accesses the detail page URL (such as refreshing the page), usePosts will re-fetch data. This is correct behavior - because the usePosts instance on the home page and the usePosts instance on the detail page are independent, each calling its own useEffect.


useDarkMode — Switch Dark Mode with One Line of Code

Example

// File path: src/hooks/useDarkMode.js

import

{

useState

,

useEffect

}

from

'react'

export

function

useDarkMode

(

)

{

 

// Read previous settings from localStorage

 

const

[

isDark

,

setIsDark

]

=

useState

(

(

)

=>

{

   

return

localStorage.

getItem

(

'blog-theme'

)

===

'dark'

 

}

)

 

// When isDark changes, sync to DOM and localStorage

  useEffect

(

(

)

=>

{

   

if

(

isDark

)

{

      document.

documentElement

.

classList

.

add

(

'dark'

)

      localStorage.

setItem

(

'blog-theme'

,

'dark'

)

   

}

else

{

      document.

documentElement

.

classList

.

remove

(

'dark'

)

      localStorage.

setItem

(

'blog-theme'

,

'light'

)

   

}

 

}

,

[

isDark

]

)

 

function

toggleDark

(

)

{

    setIsDark

(

!

isDark

)

 

}

 

return

{

isDark

,

toggleDark

}

}

Use in NavBar:

Example

// File path: src/components/NavBar.jsx

import

{

useDarkMode

}

from

'../hooks/useDarkMode'

function

NavBar

(

)

{

 

const

{

isDark

,

toggleDark

}

=

useDarkMode

(

)

 

return

(

   

<

header className

=

"navbar"

     

<

a href

=

"/"

className

=

"logo"

RUNOOB Blog

a

     

<

nav

<

a href

=

"/"

Home

a

       

<

button className

=

"theme-btn"

onClick

=

{

toggleDark

}

         

{

isDark

?

'☀ Light'

:

'☾ Dark'

}

       

button

     

nav

   

header

 

)

}

export

default

NavBar

CSS Variables for Theme Switching

Example

/* File path: src/index.css (global styles) */

/* Light mode (default) */

:root

{

  --bg-primary

:

#f5f5f5

;

  --bg-card

:

#ffffff

;

  --text-primary

:

#333333

;

  --text-secondary

:

#666666

;

  --border-color

:

#eeeeee

;

}

/* Dark mode */

html

.dark

{

  --bg-primary

:

#1a1a2e

;

  --bg-card

:

#16213e

;

  --text-primary

:

#e0e0e0

;

  --text-secondary

:

#a0a0a0

;

  --border-color

:

#2a2a4a

;

}

body

{

 

background

:

var

(

--bg-primary

)

;

 

color

:

var

(

--text-primary

)

;

}

.card

,

.article-card

{

 

background

:

var

(

--bg-card

)

;

 

border

:

1px

solid

var

(

--border-color

)

;

}


React Custom Hook vs Vue3 Composable

Feature React Custom Hook Vue3 Composable
Naming Convention Starts with use Starts with use
Nature A function that uses React Hooks A function that uses Vue3 APIs
Reactive Triggered by the setter returned from useState Automatically tracked via ref/reactive
Call restrictions Only at the top level of function components can only be used inside