Verified Commit 407f7253 authored by Florent Chehab's avatar Florent Chehab
Browse files

fix(useSharedState): kind of safer

parent 3ea4525d
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import usePersistentState, { getPersistedValue } from "./usePersistentState";
import useConstantState from "./useConstantState";
......@@ -23,8 +23,17 @@ function useSharedState(key, valueIfNoPrevious) {
// A bit of optimization in order no to save to the persisted state every time
const [state, setState] = useState(persistedState);
// hack with useConstantState to make sure it is run NOW
useConstantState(() => {
useEffect(() => {
return () => {
// Cleaning listeners list on unmount
if (listenersByKey.has(key)) {
listenersByKey.get(key).delete(setState);
}
};
}, []);
// hack with useMemo to make sure it is run NOW
useMemo(() => {
// Subscribe as a listener
if (!listenersByKey.has(key)) listenersByKey.set(key, new Set());
listenersByKey.get(key).add(setState);
......@@ -32,13 +41,6 @@ function useSharedState(key, valueIfNoPrevious) {
// small check to make sure the value is coherent
const valueInStore = getPersistedValue(key);
if (valueInStore !== state) setState(valueInStore);
});
useEffect(() => {
return () => {
// Cleaning listeners list on unmount
listenersByKey.get(key).delete(setState);
};
}, []);
const setStateOut = useCallback(
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment