今日已更新 313 条资讯 | 累计 38170 条内容
关于我们

Why My React App Still Runs on Singleton Classes

Soham Mondal 2026年09月01日 14:55 0 次阅读 来源:Dev.to

React spent the last decade training developers that a class is a code smell. Class components got deprecated, hooks won, and "just write a function" became the default advice for almost everything. That advice runs into a wall the moment a piece of code has to run outside a component: an HTTP interceptor, an event listener, a background task, a deep-link handler. None of those have a render tree to sit inside, which means none of them can call a hook. That's not a style opinion. It's a hard constraint. It's also the reason core pieces of infrastructure in most non-trivial React codebases — auth tokens, feature flags, routing rules, device identity, analytics — end up as classes, usually singletons, imported directly instead of consumed through a hook or a context provider. The render-tree boundary problem A hook only exists while its component exists. useState allocates memory tied to a place in React's tree; the moment that component unmounts, the state is gone, and before it mounts, the state isn't reachable at all. That's fine for almost everything a component owns. It stops being fine the moment something outside the tree needs the same piece of state. Authentication is the clearest version of this. A typical setup keeps the access token in a hook, refreshed on a timer, exposed to whatever component needs it: export const useSessionTokens = (): UseSessionTokens => { const [ tokens , setTokens ] = React . useState < AuthTokens | null > ( null ); const refreshAccessToken = async () => { if ( ! tokens ?. refreshToken ) return ; const newTokens = await refreshAndSetTokens ({ refreshToken : tokens . refreshToken }); setTokens ( newTokens ); return newTokens ; }; // ... return { tokens , refreshAccessToken , /* ... */ }; }; Perfectly normal hook. The problem shows up one layer down: an HTTP client's request interceptor is a plain function, registered once at app boot, running completely outside React's render tree. It can't call useSessionTokens() — it isn't a compon

本文内容来源于互联网,版权归原作者所有
查看原文