DEV Community

inno
inno

Posted on

react中useStateCallback的封装

target:当state更新后,调用回调函数

  • useEffect会在state的数据变化后

  • useRef存储、调用回调函数

Package

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

export const useStateCallback=<T>(initialState: T | (() => T))=>{
  const [state, setState] = useState<T>(initialState)
 const ref= useRef<any>()
  const setStateCallback=(value: T | ((prevState: T) => T),callback:Function)=>{  
    ref.current=callback
     setState(value)
  }
  useEffect(() => {
    ref.current&&ref.current(state)
  }, [state])
  return {state,setStateCallback}
}
Enter fullscreen mode Exit fullscreen mode

Call

import { Button } from 'antd'
import { useStateCallback } from './hooks'

 const App = () => {
 const {state,setStateCallback}= useStateCallback<number>(1)
  const click=()=>{
    setStateCallback(state=>state+1,(stateUpdated:number)=>{
      console.log("after updating data",stateUpdated);
    })
  }
  return (
    <div>  
     count:{state}
     <Button onClick={click}></Button>
   </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

Outcome

Image description

Top comments (0)