Skip to main content

useDeepCompareEffect

useDeepCompareEffect is a custom hook based on useEffect but allows non-primitive dependencies.

Usage

import { useDeepCompareEffect } from '@antscorp/antsomi-hooks'
import { createConnection } from './chat.js'

interface ChatRoomProps {
options: Record<string, string | number>
}

function ChatRoom({ options }: ChatRoomProps) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234')

useDeepCompareEffect(() => {
const connection = createConnection(serverUrl, options)
connection.connect()
return () => {
connection.disconnect()
}
}, [serverUrl, options])
// ...

return <div>Your component</div>
}

API

useDeepCompareEffect(setup, dependencies): void

Parameters

NameTypeDescription
setup() => voidThe function with your Effect's logic.
dependenciesanyThe list of all reactive values referenced inside of the setup code.

Returns

void

Hook

import { useEffect, useRef } from 'react'
import isEqual from 'react-fast-compare'

function useDeepCompareMemoize(value) {
const ref = useRef()

if (!isEqual(value, ref.current)) {
ref.current = value
}

return ref.current
}

export function useDeepCompareEffect(callback, dependencies) {
useEffect(callback, dependencies.map(useDeepCompareMemoize))
}