sokko-g/website/src/hooks/useKeyedState.js
Shinuwa 7c0b72f914
Some checks failed
Deploy Sokko G / deploy (push) Failing after 3s
Initialize session state by page and module identity
2026-09-11 14:05:41 +02:00

21 lines
757 B
JavaScript

// Rôle : initialise un état local par clé et ignore les setters d'une identité remplacée.
import { useCallback, useState } from "react";
export function useKeyedState(key, initialize) {
const [state, setState] = useState(() => ({ key, value: initialize(key) }));
let current = state;
if (!Object.is(state.key, key)) {
current = { key, value: initialize(key) };
setState(current);
}
const setValue = useCallback((value) => {
setState((previous) => {
if (!Object.is(previous.key, key)) return previous;
const next = typeof value === "function" ? value(previous.value) : value;
return Object.is(previous.value, next) ? previous : { key, value: next };
});
}, [key]);
return [current.value, setValue];
}