
React: Singletons aren't as evil as you think
In the world of React, the humble singleton gets a bit of a bad rap. It is often dismissed as a messy shortcut to global state, one that is difficult to track and even harder to test. But what if I told you the singleton is not the architectural terror you have been led to believe? What if I showed you it is actually powerful, lightweight and remarkably simple to implement? You might think me mad, but I am about to convince you that singletons are not the villains of the story. The Singleton Scepticism Historically, if you wanted to pull data from a singleton in React, you often had to wait for the app to re-render for some other reason. You might have seen a manual sync button or a poll used to bridge the gap, but it was rarely pretty. import { useState , useEffect , useCallback } from ' react ' ; import SomeSingleton from ' @/singletons/some ' ; export function ReactElement () { const [ singletonData , setSingletonData ] = useState ( SomeSingleton . data || null ); /** * Sync singlet
Continue reading on Dev.to React
Opens in a new tab



