Files
element-call-Github/src/useStableValue.ts
T
Timo K.andClaude Fable 5.1 a010cc983f Compare the component's config by value
Everything downstream of the component's params — the mute state, the
call view model and with it the media connection — is keyed on the
identity of the params object, which was memoised on the identity of
the `config` prop. A host writing `config={{ ... }}` inline, which is
the natural way to write it, therefore tore the whole call down on
every render. The harness happened to pass a constant, so nothing
noticed.

`useStableValue` hands out the same object for as long as a deep
comparison says nothing changed, so an inline config costs nothing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 13:49:19 +02:00

30 lines
985 B
TypeScript

/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useState } from "react";
import { isEqual } from "lodash-es";
/**
* Returns a value whose identity only changes when its contents do.
*
* For a prop that a caller is likely to write inline — an options object, say
* — so that a fresh but equal object on every render does not restart whatever
* depends on it. Deep equality by default.
*/
export function useStableValue<T>(
value: T,
equals: (a: T, b: T) => boolean = isEqual,
): T {
const [stable, setStable] = useState(value);
if (equals(stable, value)) return stable;
// Setting state during render makes React re-run this render immediately
// with the new state, at which point the two are identical and the stored
// one is returned — so the identity handed out is consistent.
setStable(value);
return value;
}