import {useCallback, useRef, useState} from 'react';
import {shallowEqual} from "../utils/shallowEqual";
function useEnhancedState(initialState: any) {
const [state, setState] = useState(initialState);
// 与state数值是一致的,为避免产生新的updateState使用它与前一个值进行比较。
const stateRef = useRef(initialState);
// 永远指向最新的state
const currentRef = useRef(initialState);
currentRef.current = state;
// 更新state:只有当nextState与当前state产生变化时才会触发渲染,优化性能
const updateState = useCallback((nextState: any) => {
if (typeof nextState !== "function") {
currentRef.current = nextState;
if (shallowEqual(stateRef.current, nextState)) {
return;
}
stateRef.current = nextState;
}
setState(nextState);
}, []);
// 在render之前,就能获取最新的state
const getCurrent = useCallback(() => {
return currentRef.current;
}, []);
return [state, updateState, getCurrent];
}
export {
useEnhancedState
}
使用方法:通过第三个参数可以在render之前,就能获取最新的state
import {useEnhancedState} from "./hooks/useEnhancedState";
import './App.css'
function App() {
const [count, setCount, getCount] = useEnhancedState(0)
return (
<div className="App">
<div className="card">
<button onClick={() => {
// setCount( count + 1);
// setCount( count + 1);
// setCount( count + 1);
// setCount( count + 1);
// setCount( (count:any)=> count + 1);
// setCount( (count:any)=> count + 1);
// setCount( (count:any)=> count + 1);
// setCount( (count:any)=> count + 1);
// setCount(getCount() + 1);
// setCount(getCount() + 1);
// setCount(getCount() + 1);
// setCount(getCount() + 1);
}}>
count is {count}
</button>
</div>
</div>
)
}
export default App;