ITADN

Draft: Add event.persisted check in restore handler to prevent unnecessary rehydration on page load

#66Pull Requestd8corp 创建于 2026-02-04
D
d8corpcommented
#### 📌 Summary This PR enhances the reliability of the `persistentAtom` store hydration logic by introducing a check for `event.persisted` in the `pageshow` event handler (`restore` function). This ensures that state is only restored from persistent storage when the page is being **restored from the bfcache** (back-forward cache), and **not** on the initial page load — where the store is already correctly initialized from `localStorage`. #### 🔍 Problem Previously, the `restore` function was called on **every** `pageshow` event — including the initial page load. This caused redundant and potentially conflicting rehydration of the store from `localStorage`. #### ✅ Solution Added this guard clause in the `restore` function: ```js if (!event.persisted) return ``` This ensures that state restoration only occurs when: - The page is being restored from the browser’s **bfcache** (e.g., after navigating back/forward) - The page was **not** freshly loaded This matches the intended behavior of persistent storage: **recover** state after a cached navigation, not **reapply** it on every load. #### 💡 Why This Matters - **Performance**: Avoids redundant JSON parsing and state updates. - **User Experience**: Prevents UI flickering or state resets on page load. - **Correctness**: Aligns with browser semantics — `pageshow.persisted === true` is the standard way to detect bfcache restoration. #### 🛠 Changes - ✅ Added `if (!event.persisted) return` to `restore` function in `persistentAtom` - ✅ Removed redundant `restore()` call from `onMount` (it was triggering hydration on load, conflicting with initial store value) - ✅ Kept `restore` as event listener for `pageshow` — now only triggers on bfcache restore - ✅ No breaking changes — behavior is more correct, not different in normal cases - ✅ All tests and utilities (`useTestStorageEngine`, etc.) remain unchanged and compatible #### 📚 Background - [MDN: `pageshow` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event) - [bfcache (back-forward cache)](https://web.dev/bfcache/) - `event.persisted` is `true` if the page was restored from bfcache, `false` on initial load. --- ### 📌 Recommendation This is a **bug fix** and **performance improvement**, not a feature. It makes the library behave more predictably in modern browsers with bfcache enabled (which is now the default in Chrome, Firefox, and Safari). **Merge this to improve user experience and eliminate edge-case bugs.**
合并状态:未合并 1 条评论