2022-05-22 08:36:05 +00:00
|
|
|
import { isEqual } from 'lodash'
|
2022-04-06 18:55:59 +00:00
|
|
|
import { useMemo, useRef, useState } from 'react'
|
|
|
|
|
|
|
|
export const useStateCheckEquality = <T>(initialState: T) => {
|
|
|
|
const [state, setState] = useState(initialState)
|
|
|
|
|
|
|
|
const stateRef = useRef(state)
|
|
|
|
stateRef.current = state
|
|
|
|
|
|
|
|
const checkSetState = useMemo(
|
|
|
|
() => (newState: T) => {
|
|
|
|
const state = stateRef.current
|
2022-05-22 08:36:05 +00:00
|
|
|
if (!isEqual(state, newState)) {
|
2022-04-06 18:55:59 +00:00
|
|
|
setState(newState)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
[stateRef]
|
|
|
|
)
|
|
|
|
|
|
|
|
return [state, checkSetState] as const
|
|
|
|
}
|