什么人每天靠运气赚钱| 阴虚火旺吃什么水果| 经常流鼻血什么原因| 医学是什么| 珍珠五行属什么| 卧推60公斤什么水平| 颅内出血有什么症状| 属兔本命佛是什么佛| 尿崩症是什么意思| 大腿内侧发黑是什么原因| 男人吃叶酸片有什么好处| 胎监不过关是什么原因| 十指连心是什么意思| 包涵是什么意思| 精神病是什么意思| 全脂乳粉是什么| 宝宝睡眠不好是什么原因| 高处不胜寒是什么意思| fop是什么意思| 胎盘做成胶囊吃有什么好处| 情不自禁的禁是什么意思| 壁虎进家里预示什么| 什么叫韵母| bf什么意思| 甲亢是什么引起的| 牙齿出血是什么病表现出来的症状| 老年人助听器什么牌子好| palace什么牌子| o2o什么意思| 乌黑乌黑的什么| 高挑是什么意思| 喝什么茶去火| 世子是什么意思| 县团级是什么级别| 白细胞高一点点是什么原因| 静脉曲张挂什么科| 梦到好多蛇是什么意思| 淋巴结肿大看什么科室最好| 默哀是什么意思| 口腔发粘是什么原因| 经常闪腰是什么原因引起的| 男人更年期有什么症状有哪些表现| 双非是什么| 2008年出生的属什么| 起酥油是什么油| 尿细菌高是什么原因| 经略相公是什么官| 银杏树叶子像什么| 电音是什么意思| 太行山在什么地方| 扑街是什么意思| 老妈子是什么意思| 左边后背疼是什么原因| 画饼什么意思| 清洁度三度什么意思| 小缺血灶是什么意思| 六畜大宝在农家是什么生肖| ch是什么| 鸡头上长痘痘用什么药| 什么是老年斑图片| 宣字五行属什么| 胃病可以吃什么水果| 颈椎病吃什么药效果好| 内退是什么意思| 减肥期间可以喝什么茶| 心跳过缓吃什么药| 诺如病毒是什么| 至字五行属什么| 什么是尿常规检查| 什么时候看到的月亮最大| 一个三点水一个及念什么| 夏枯草治什么病| 甘之如饴是什么意思| 大姨妈量多是什么原因| 时点是什么意思| 孕妇喝什么牛奶好| 难道是什么意思| 什么的垂下| 灰色五行属什么| 什么是低碳饮食| ambush是什么牌子| 引产是什么意思| 尿遁什么意思| 蓝脸的窦尔敦盗御马是什么歌| 打车用什么软件| mri是什么检查项目| 水杨酸有什么作用| 女流之辈是什么意思| 出家需要什么条件| 巴图是什么意思| 火车代表什么生肖| longines是什么牌子| 国师代表什么生肖| 男人时间短吃什么药好| 瘦马是什么意思| 什么动物最聪明| 月经褐色是什么原因| 什么网卡好| 83年猪是什么命| ga是什么| 念力是什么意思| 走路气喘是什么原因| 胸闷是什么病的前兆| 一月二十号是什么星座| 急性乳腺炎是什么原因引起的| 孕酮低是什么原因造成的| 三观不合指的是什么| 盗墓笔记的结局是什么| 中午吃什么饭| 什么自如| 吸毒什么感觉| 4月13号是什么星座| pls是什么意思| 伯伯的老婆叫什么| 便秘吃什么中药| 皮质醇是什么意思| 向心性肥胖是什么意思| ca是什么病| 怀疑甲亢需要做什么检查| 颠是什么意思| 胃出血大便是什么颜色| 黑豆不能和什么一起吃| 深静脉血栓有什么症状| 预设是什么意思| 女性更年期潮热出汗吃什么药| 丁克族是什么意思| 胆囊炎有什么症状表现| img是什么意思| 女人血稠吃什么食物好| 蜂蜡是什么东西| 下肢静脉血栓挂什么科| 圣经是什么时候写的| 子宫脱垂有什么症状| 吃木瓜有什么作用| 轻度脑梗吃什么药最好| 爱出汗是什么原因| 疮疖是什么意思| 白茶什么季节喝好| 下面痒用什么清洗最好| 为什么痛风就痛一只脚| 风疹病毒igg阳性是什么意思| 九天什么月| 中耳炎吃什么药最有效| 血常规24项能查出什么病| 胆黄素高是怎么回事有什么危害| 疣吃什么药能治好| 脚底出汗是什么原因女| 左手臂麻木是什么征兆| 蜂蜜什么时候喝最佳| 宫腔分离是什么意思| 餐中服用是什么意思| 安宫牛黄丸治什么病| 青蛙长什么样| ur品牌属于什么档次| 300年前是什么朝代| 手足口病吃什么食物| 什么是纳氏囊肿| 食用植物油是什么油| 红油抄手是什么| 眉尾长痘是什么原因| 首台套是什么意思| 什么是钙化结节| 尿钙是什么意思| 靖康耻指的是什么历史事件| 牛头不对马嘴是什么意思| 生地和熟地有什么区别| 女性气血不足吃什么调理| 灵芝有什么功效和作用| 什么时候同房最容易怀孕| 双子座什么性格| 外围女是什么意思| 念珠菌性阴道炎用什么药| 有恙是什么意思| 全身皮肤痒是什么原因| 肝功能挂什么科| 突然发胖要警惕什么病| 新生儿出院回家有什么讲究| 痔疮用什么药治最好效果最快| 单脐动脉是什么意思| 舌苔厚白用什么泡水喝| 复试一般会问什么问题| 梦见杀人是什么预兆| 黑色的鸟是什么鸟| 膝盖响是什么原因| 44岁月经量少是什么原因| 轴向是什么意思| 骨折恢复期吃什么好| 天蝎座什么象星座| 卡哇伊是什么意思| 甜蜜素是什么| 看望病人送什么花合适| 阳性对照是什么意思| 吃核桃有什么好处| 老是胃疼是什么原因| 神经性皮炎用什么药最好| 血管痉挛是什么原因引起的| 什么是假性狐臭| 蚂蚁代表什么风水| 咖喱饭需要什么材料| 毕是什么意思| 补气吃什么好| 手术刀口吃什么愈合快| 网盘是什么东西| 放疗和化疗有什么区别| 毛主席属什么生肖| 油菜花像什么| 为什么会做梦中梦| 腹泻拉稀水是什么原因| 为什么家里会有隐翅虫| 指鹿为马指什么生肖| 治股癣用什么药最好| 甲亢什么症状| 酒花浸膏是什么| 组织液是什么| 34周为什么不建议保胎| hr阳性是什么意思| 什么的面目| 大娘的老公叫什么| 猫睡在枕头旁说明什么| 立字五行属什么| 2020属什么生肖| 看见蝙蝠有什么预兆| 一个人是什么歌| 布蕾是什么| ou是什么意思| 917是什么星座| 什么座| 多愁善感的动物是什么生肖| 蟑螂长什么样子| 天地银行是什么意思| 什么是双| 腿纹不对称有什么影响| 腰突然疼是什么原因| 皮肤科属于什么科室| 甲钴胺不能和什么药一起服用| 与世无争是什么意思| 剑锋金命五行缺什么| 梦见好多动物是什么意思| 什么的蜡烛| 早搏有什么症状| 珅是什么意思| 牛头马面指什么生肖| 双子是什么意思| 没心没肺是什么意思| 风什么浪什么| 70大寿有什么讲究| 什么叫脘腹胀痛| 吃猪血有什么好处和坏处| 脱臼是什么感觉| 人为什么要抽烟| 加盟什么店最赚钱投资小| 1959属什么生肖| exo是什么意思啊| 什么情况下会流前列腺液| 睡觉容易惊醒是什么原因| 物欲横流是什么意思| gson是什么牌子| 美的是做什么起家的| 睫毛炎有什么症状| 618是什么星座| 秦始皇的母亲叫什么名字| 醉清风是什么意思| 被虫咬了挂什么科| apf值是什么意思| 百度
Table of Contents
What Makes a Good Custom Hook?
Why this works well:
Tips for Writing Reusable Hooks
1. Accept parameters for flexibility
2. Return a consistent structure
3. Handle side effects safely
4. Support SSR (Server-Side Rendering)
When to Build a Custom Hook?
Don’ts of Custom Hooks
Home Web Front-end Front-end Q&A Building Custom, Reusable Hooks in React

市场风格转换,两次“盛会”揭示新机会

Aug 03, 2025 pm 04:51 PM

百度 2018年,市直机关工委将围绕市委决策部署,扎实推进政治引领、支部提升、调查研究、志愿服务、作风建设、提升含氧量等“六大行动”,为全市机关更好地服务保障市委中心工作提供坚强保证。

A good custom hook in React is a reusable function starting with "use" that encapsulates stateful logic for sharing across components; it should solve a common problem, be flexible through parameters like useFetch(url, options), return a consistent structure such as an array or object, handle side effects safely with cleanup in useEffect, support SSR by checking for browser globals, and remain UI-agnostic; examples include useLocalStorage for persisting data and useEventListener for managing event listeners; you should create a custom hook when logic is repeated, independent of JSX, manages state or side effects, and can be generalized, but avoid calling hooks conditionally, passing JSX, managing UI directly, or overcomplicating when a simple utility function suffices, as custom hooks aim to reuse behavior, not markup, making components cleaner and logic more maintainable.

Building Custom, Reusable Hooks in React

Custom hooks in React are a powerful way to extract component logic into reusable functions. They let you share stateful logic—like data fetching, form handling, or subscriptions—across multiple components without duplicating code. Here’s how to build effective, reusable custom hooks.

Building Custom, Reusable Hooks in React

What Makes a Good Custom Hook?

A custom hook is just a JavaScript function whose name starts with use (e.g., useForm, useFetch). It can call other hooks like useState, useEffect, useCallback, etc. The key is encapsulation: your hook should hide internal complexity and expose a clean, intuitive API.

A good custom hook:

Building Custom, Reusable Hooks in React
  • Solves a common problem
  • Is composable and flexible
  • Doesn’t tie itself to a specific UI
  • Handles edge cases gracefully
  • Returns values and functions that are easy to use

Example: Building useLocalStorage

Let’s create a hook that syncs state with localStorage. This is useful for persisting user preferences, form inputs, or UI state.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.warn(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.warn(`Error setting localStorage key "${key}":`, error);
    }
  }, [key, value]);

  return [value, setValue];
}

Why this works well:

  • Encapsulates logic: No need to repeat localStorage checks in every component.
  • Handles errors: Prevents crashes if localStorage is full or disabled.
  • Works with any type: Accepts strings, numbers, objects, arrays via JSON.parse/stringify.
  • Easy to use:
function DarkModeToggle() {
  const [isDark, setIsDark] = useLocalStorage('darkMode', false);

  return (
    <button onClick={() => setIsDark(!isDark)}>
      {isDark ? 'Light' : 'Dark'} Mode
    </button>
  );
}

Tips for Writing Reusable Hooks

1. Accept parameters for flexibility

Let users customize behavior via arguments.

Building Custom, Reusable Hooks in React
useFetch(url, options, shouldFetch)
useForm(initialValues, onSubmit, validate)

This makes your hook adaptable to different use cases.

2. Return a consistent structure

Always return values in a predictable way—usually an array (like useState) or object.

Array return (good for named destructuring):

const [value, setValue, clear] = useInput('');

Object return (better for many values):

const { data, loading, error, refetch } = useFetch(url);

Choose based on how many things you’re returning.

3. Handle side effects safely

Use useEffect cleanup to avoid memory leaks.

Example: useEventListener

function useEventListener(eventName, handler, element = window) {
  useEffect(() => {
    const target = element.current || element;
    target.addEventListener(eventName, handler);

    return () => target.removeEventListener(eventName, handler);
  }, [eventName, handler, element]);
}

Cleanup ensures the event listener is removed when the component unmounts.

4. Support SSR (Server-Side Rendering)

Avoid referencing browser globals like window or localStorage during SSR.

Improved useLocalStorage check:

if (typeof window === 'undefined') return [initialValue, setValue];

Or use a check inside:

const canUseDOM = typeof window !== 'undefined';

When to Build a Custom Hook?

Ask yourself:

  • Is this logic repeated in multiple components?
  • Is it independent of specific JSX?
  • Does it manage state or side effects?
  • Can it be generalized?

If yes → make a custom hook.

Common patterns:

  • useMediaQuery(query) → responsive logic
  • useOutsideClick(ref, callback) → detect clicks outside an element
  • useDebounce(value, delay) → delay state updates
  • useScrollPosition() → track scroll

Don’ts of Custom Hooks

  • ? Don’t call hooks conditionally (follow the Rules of Hooks)
  • ? Don’t pass children or JSX into hooks (they’re not components)
  • ? Don’t manage UI directly—keep hooks UI-agnostic
  • ? Don’t overcomplicate—sometimes a utility function is enough

Building custom hooks is about reusing behavior, not markup. When done right, they make your components cleaner, your logic more testable, and your app easier to maintain.

Basically: if you're copying and pasting useEffect or useState logic, it's probably time to make a custom hook.

The above is the detailed content of Building Custom, Reusable Hooks in React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How does React handle focus management and accessibility? How does React handle focus management and accessibility? Jul 08, 2025 am 02:34 AM

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Describe the difference between shallow and full rendering in React testing. Describe the difference between shallow and full rendering in React testing. Jul 06, 2025 am 02:32 AM

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

What is the significance of the StrictMode component in React? What is the significance of the StrictMode component in React? Jul 06, 2025 am 02:33 AM

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Vue with TypeScript Integration Guide Vue with TypeScript Integration Guide Jul 05, 2025 am 02:29 AM

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

How to handle forms in Vue How to handle forms in Vue Jul 04, 2025 am 03:10 AM

There are three key points to be mastered when processing Vue forms: 1. Use v-model to achieve two-way binding and synchronize form data; 2. Implement verification logic to ensure input compliance; 3. Control the submission behavior and process requests and status feedback. In Vue, form elements such as input boxes, check boxes, etc. can be bound to data attributes through v-model, such as automatically synchronizing user input; for multiple selection scenarios of check boxes, the binding field should be initialized into an array to correctly store multiple selected values. Form verification can be implemented through custom functions or third-party libraries. Common practices include checking whether the field is empty, using a regular verification format, and displaying prompt information when errors are wrong; for example, writing a validateForm method to return the error message object of each field. You should use it when submitting

Server-Side Rendering with Next.js Explained Server-Side Rendering with Next.js Explained Jul 23, 2025 am 01:39 AM

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

A Deep Dive into WebAssembly (WASM) for Front-End Developers A Deep Dive into WebAssembly (WASM) for Front-End Developers Jul 27, 2025 am 12:32 AM

WebAssembly(WASM)isagame-changerforfront-enddevelopersseekinghigh-performancewebapplications.1.WASMisabinaryinstructionformatthatrunsatnear-nativespeed,enablinglanguageslikeRust,C ,andGotoexecuteinthebrowser.2.ItcomplementsJavaScriptratherthanreplac

What is content security policy CSP What is content security policy CSP Jul 04, 2025 am 03:21 AM

Content Security Policy (CSP) prevents attacks such as XSS by limiting the loading source of web page resources. Its core mechanism is to set a whitelist to prevent unauthorized scripts from being executed. The steps to enable include: 1. Define the policy and clarify the allowed resource sources; 2. Add Content-Security-PolicyHTTP header to the server; 3. Use Report-Only mode to test and debug in the initial stage; 4. Continuous monitoring and optimization strategies to ensure that they do not affect normal functions. Notes include handling inline scripts, careful use of third-party resources, compatibility support, and other irreplaceable security measures.

See all articles
女人喝胶原蛋白有什么好处 毛囊炎吃什么药最有效 羊肉水饺配什么菜好吃 熟视无睹什么意思 pct是什么
正念是什么 什么是脑中风 戊五行属什么 湿气重能吃什么水果 hsv病毒是什么意思
黑今读什么 结扎后需要注意什么 常务副省长是什么级别 女性胆囊炎有什么症状 手抖什么原因
缺锌吃什么食物和水果 没有什么 腹泻能吃什么水果 乳酸偏高是什么意思 洋葱不能跟什么一起吃
嗪读什么hcv9jop3ns3r.cn 普洱茶有什么功效与作用hcv8jop5ns1r.cn 折服是什么意思hcv8jop0ns1r.cn 蜂王浆什么时间吃最好hcv7jop4ns8r.cn 气虚吃什么补最快wzqsfys.com
什么原因导致卵巢早衰hcv8jop6ns3r.cn 什么的天空hcv8jop9ns0r.cn 什么字五行属金hcv9jop1ns5r.cn 背靠背什么意思hcv9jop6ns8r.cn 猫在风水上代表什么hcv7jop7ns4r.cn
梦到老房子是什么意思hcv7jop7ns0r.cn 梦见吃樱桃是什么意思hcv8jop6ns6r.cn 子宫平位是什么意思hcv9jop2ns0r.cn 疟疾是什么意思hcv9jop5ns6r.cn 开指是什么意思naasee.com
夜尿频繁是什么原因hcv9jop6ns0r.cn 为什么脚底板发黄hcv9jop0ns2r.cn 巩膜是什么部位qingzhougame.com 堂哥的儿子叫什么hcv8jop7ns2r.cn 肾气亏虚吃什么中成药hcv9jop3ns0r.cn
百度