引用最新的state
API
useRefState<S> (
initialState?: S | (() => S)
): [S | undefined, Dispatch<SetStateAction<S | undefined>>, MutableRefObject<S | undefined>]
Params
属性描述必选类型默认值
initialState初始值否any | ()=>any-
Return
属性描述
statestate
setState更新state的值
refref.current永远为最新的值
Use
import React, { useCallback } from 'react'
import { useRefState } from 'nchooks'
function App() {
const [count, setCount, countRef] = useRefState(0)
const handleIncr = useCallback(() => {
setCount(countRef.current + 1)
}, [])
useEffect(() => {
return () => {
// 在组件卸载时保存当前的count
saveCount(countRef.current)
}
}, [])
return (
<div>
{count}: <button onClick={handleIncr}>increment</button>
</div>
)
}
export default App;