当前位置:网站首页>useMemo,memo,useRef等相关hooks详解

useMemo,memo,useRef等相关hooks详解

2022-07-05 14:32:00 原谅我不够洒脱

useMemo

主要是用来做数据计算,并带有缓存不会重复计算,相当于vue的computed

import React,{
     useRef, useState, useEffect, useMemo, memo } from 'react'

export default function text() {
    
	const [height, setHeight] = useState(66)
	const memoizedCallback = useMemo(
	  () => {
    
	    return height + '测试Callback'
	  },
	  [height],
	)
	return (
		<div>{
    memoizedCallback}</div>
	)
}

memo

memo:防止子组件无用更新(当全局content发生变化时还是会更新,memo第二个参数可以阻止,但是官方建议少用)

import React,{
     useRef, useState, useEffect, useMemo, memo } from 'react'



const Son = function () {
    

  return (
    <div className='child-box'>

    </div>
  )
}
function areEqual(prevProps, nextProps) {
    
  return prevProps === nextProps // 你不想它更新就返回true
}
const HooksChild = memo(Son, areEqual) // 第二个参数可以不传

export default function text() {
    
	const [height, setHeight] = useState(66)
	const memoizedCallback = useMemo(
	  () => {
    
	    return height + '测试Callback'
	  },
	  [height],
	)
	return (
		<div>
			<HooksChild/>
		</div>
	)
}

useRef

给你提供一个封闭的空间来储存变量,组件重新渲染和他无关,除非你自己去改

import {
     useRef, useState } from 'react';

const useTimer = (step = 1) => {
    
  const timer = useRef(null)
  const [ num, setNum ] = useState(0)
  const start = () => {
    
    // const timeout = setInterval(() => {
    
    // setNum((num)=>num + 1)
    // }, step * 1000)
    timer.current = null
  }
  const clear = () => {
    
    setNum(0)
    clearInterval(timer.current)
  }
  return {
    
    num,
    start,
    clear
  }
}
export default useTimer

完整例子自定义hooks封装不会反复创建的定时器

useContext,useReducer

useContext 全局变量,useReducer使用和useState使用方法差不多

完整例子useContext+useReducer实现全局状态共享

原网站

版权声明
本文为[原谅我不够洒脱]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44441196/article/details/117328033