React之useRef hook

介绍

useRef是react的自定义hook,它用来引用一个不需要渲染的值。这篇文章会介绍useRef的简单用法。

使用场景

1.实现节流

通过useRef实现节流功能,在限制时间内多次提交,已第一次提交为准。

useThrottle.jsx

javascript 复制代码
import {useEffect, useRef, useState} from "react";

import {useEffect, useRef, useState} from "react";

export const useThrottle = (state, timeout) => {
    // 计时器引用
    const timeoutRef = useRef(null);

    // 计时器执行结束
    const existTimeOut = useRef(false);

    // 节流值
    const [throttleValue, setThrottleValue] = useState(state);


    useEffect(()=>{

        // 存在定时器
        if (existTimeOut.current){
            return;
        }
        existTimeOut.current = true;
        // 设置节流值
        timeoutRef.current = setTimeout(()=>{
            setThrottleValue(state);
            existTimeOut.current = false;
        }, timeout)

    },[state])

    return throttleValue;
}

app.jsx(使用样例)

javascript 复制代码
import './App.css';
import {useEffect, useState} from "react";
import {useThrottle} from "./demo/UseRefDemo";



const App =()=>{
    const [state, setState] = useState('')
    const throttleState = useThrottle(state, 10000);
    useEffect(()=>{
        console.log('延迟执行:' + throttleState);
    }, [throttleState])
    return <>
         用戶名: <input type='text' value={state} onChange={(e)=> setState(e.target.value)}/>
    </>
}
export  default App

实现效果

2.操作dom元素

javascript 复制代码
export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        聚焦输入框
      </button>
    </>
  );
}

实现效果

相关推荐
飞天狗6 小时前
长列表滚动卡顿怎么破:虚拟列表选型 + react-virtuoso 实战调优指南
react.js·性能优化
binbin_528 小时前
React 井字棋教程:用一个小游戏理解组件和状态
前端·react.js·前端框架
张元清9 小时前
React useObjectUrl Hook:预览文件与 Blob,不留内存泄漏(2026)
javascript·react.js
真的想不出名儿13 小时前
Md编辑器整合-react
前端·react.js·编辑器
牛仔只喝牛奶1 天前
多端跨端技术选型:小程序 + H5 + App 的两栈拆分落地
react native·react.js
wear工程师1 天前
setState 到底是不是异步的?这题从 React 16 问到 18,标准答案早就变了
react.js·面试
wanghowie1 天前
LangGraph4j 落地(二)— ReAct 多步工具与 trace 扩展
前端·react.js·前端框架
csj501 天前
前端基础之《React(11)—state声明式》
前端·react.js
张元清1 天前
React useLocalStorage Hook:SSR 安全的持久化状态(2026)
javascript·react.js
析数塔1 天前
2026前端框架深度解析:React Compiler、Angular Zoneless、Vue 3.5重写游戏规则
前端·vue.js·react.js