You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React路由切换后自定义useScript Hook失效问题咨询

Why Your Custom useScript Hook Fails on Route Changes (and the Fix Explained)

Let's break down exactly why your original hook stopped working after route changes, and why moving the logic directly into the component's useEffect fixed things:

1. The Global Cache Blocked Re-Execution

Your original useScript hook relied on a global cachedScripts array to track loaded script URLs. Here's the sequence of events:

  • On the first mount of the Scripts component, scripts were added to the cache and injected into the DOM, working as expected.
  • When you switched routes, the Scripts component unmounted. When you navigated back, it mounted again—but since cachedScripts is a global variable (persists across component mounts/unmounts), the hook saw the URLs were already in the cache and skipped re-injecting the scripts.

Many scripts tied to page-specific functionality need to re-run when the component mounts again (they might clean up state on unmount, or require re-initialization for the new page context). The cache prevented this critical re-execution.

2. The Hook's useEffect Only Ran Once

The useEffect in your custom hook had an empty dependency array [], meaning it only executed once per hook instance. When the component re-mounted after a route change, even though a new hook instance was created, the global cache meant it never reached the code that injects scripts again.

In contrast, moving the logic directly into the component's useEffect (also with an empty dependency array) ensures that every time the Scripts component mounts—including after route changes—the effect runs from scratch. It creates new <script> elements and injects them into the DOM every time.

3. Browser Script Execution Rules

Browsers will re-fetch and re-execute a script every time you inject a new <script> element with the same src (even if the script is already in the browser's cache). Your original hook avoided this by reusing the cache, so the script never ran again after the first mount. The component-level useEffect bypasses this restriction, ensuring the script runs on every mount, which fixed your route change issue.

A Quick Optimization Note

If you want to avoid re-injecting scripts unnecessarily (while still ensuring they work on route changes), you could adjust the hook to track scripts per component instance or check if the script is actually present in the DOM before re-injecting—but for your use case, the component-level useEffect is a simple, effective fix.

内容的提问来源于stack exchange,提问作者Akashii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:11:40