Initialize session state by page and module identity
Some checks failed
Deploy Sokko G / deploy (push) Failing after 3s
Some checks failed
Deploy Sokko G / deploy (push) Failing after 3s
This commit is contained in:
parent
4f644ca116
commit
7c0b72f914
8 changed files with 177 additions and 19 deletions
21
website/src/hooks/useKeyedState.js
Normal file
21
website/src/hooks/useKeyedState.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
// 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];
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue