Przeglądaj źródła

fix(app): avoid setState-in-render warning in useHydrateGlobalEachAtoms

Replace `dangerouslyForceHydrate: true` with a split approach: keep
`useHydrateAtoms` for the initial hydration (so children see correct
values on first render) and sync subsequent `commonEachProps` changes
via `useEffect` + `useSetAtom`. This prevents the "Cannot update a
component while rendering a different component" warning caused by
forcibly writing atoms during render on every route transition.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Yuki Takei 1 dzień temu
rodzic
commit
aac30f02d2
1 zmienionych plików z 21 dodań i 1 usunięć
  1. 21 1
      apps/app/src/states/global/hydrate.ts

+ 21 - 1
apps/app/src/states/global/hydrate.ts

@@ -1,3 +1,5 @@
+import { useEffect } from 'react';
+import { useSetAtom } from 'jotai';
 import { useHydrateAtoms } from 'jotai/utils';
 
 import type { CommonEachProps, CommonInitialProps } from '~/pages/common-props';
@@ -69,11 +71,29 @@ export const useHydrateGlobalInitialAtoms = (
 export const useHydrateGlobalEachAtoms = (
   commonEachProps: CommonEachProps,
 ): void => {
+  // Initial hydration: ensure atoms are populated before children read them on first render
   const tuples = [
     createAtomTuple(currentPathnameAtom, commonEachProps.currentPathname),
     createAtomTuple(currentUserAtom, commonEachProps.currentUser),
     createAtomTuple(isMaintenanceModeAtom, commonEachProps.isMaintenanceMode),
   ];
+  useHydrateAtoms(tuples);
+
+  // Subsequent sync (e.g. route transitions): run in effect to avoid
+  // "setState during render of a different component" warnings
+  const setCurrentPathname = useSetAtom(currentPathnameAtom);
+  const setCurrentUser = useSetAtom(currentUserAtom);
+  const setIsMaintenanceMode = useSetAtom(isMaintenanceModeAtom);
+
+  useEffect(() => {
+    setCurrentPathname(commonEachProps.currentPathname);
+  }, [commonEachProps.currentPathname, setCurrentPathname]);
+
+  useEffect(() => {
+    setCurrentUser(commonEachProps.currentUser);
+  }, [commonEachProps.currentUser, setCurrentUser]);
 
-  useHydrateAtoms(tuples, { dangerouslyForceHydrate: true });
+  useEffect(() => {
+    setIsMaintenanceMode(commonEachProps.isMaintenanceMode);
+  }, [commonEachProps.isMaintenanceMode, setIsMaintenanceMode]);
 };