diff --git a/web/hooks/use-contract.ts b/web/hooks/use-contract.ts index 2ccc651a..ebff7dce 100644 --- a/web/hooks/use-contract.ts +++ b/web/hooks/use-contract.ts @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' import { Contract, listenForContract } from '../lib/firebase/contracts' +import { useStateCheckEquality } from './use-state-check-equality' export const useContract = (contractId: string) => { const [contract, setContract] = useState( @@ -14,12 +15,14 @@ export const useContract = (contractId: string) => { } export const useContractWithPreload = (initial: Contract | null) => { - const [contract, setContract] = useState(initial) + const [contract, setContract] = useStateCheckEquality( + initial + ) const contractId = initial?.id useEffect(() => { if (contractId) return listenForContract(contractId, setContract) - }, [contractId]) + }, [contractId, setContract]) return contract } diff --git a/web/hooks/use-state-check-equality.ts b/web/hooks/use-state-check-equality.ts new file mode 100644 index 00000000..b7dd1370 --- /dev/null +++ b/web/hooks/use-state-check-equality.ts @@ -0,0 +1,21 @@ +import _ from 'lodash' +import { useMemo, useRef, useState } from 'react' + +export const useStateCheckEquality = (initialState: T) => { + const [state, setState] = useState(initialState) + + const stateRef = useRef(state) + stateRef.current = state + + const checkSetState = useMemo( + () => (newState: T) => { + const state = stateRef.current + if (!_.isEqual(state, newState)) { + setState(newState) + } + }, + [stateRef] + ) + + return [state, checkSetState] as const +} diff --git a/web/hooks/use-user.ts b/web/hooks/use-user.ts index 861ec4bf..022045b9 100644 --- a/web/hooks/use-user.ts +++ b/web/hooks/use-user.ts @@ -1,3 +1,4 @@ +import _ from 'lodash' import { useEffect, useState } from 'react' import { PrivateUser } from '../../common/user' import { @@ -6,17 +7,20 @@ import { listenForUser, User, } from '../lib/firebase/users' +import { useStateCheckEquality } from './use-state-check-equality' export const useUser = () => { - const [user, setUser] = useState(undefined) + const [user, setUser] = useStateCheckEquality( + undefined + ) - useEffect(() => listenForLogin(setUser), []) + useEffect(() => listenForLogin(setUser), [setUser]) const userId = user?.id useEffect(() => { if (userId) return listenForUser(userId, setUser) - }, [userId]) + }, [userId, setUser]) return user }