40 ms·
Ask HN: What is your favorite front end state management solution?
Did you already build nontrivial applications with it? Where does it shine? What are the cons? What did you try before, which didn't work for you?
- zspace2 4y agoOn angular, we use ngrx (Reactive State for Angular) https://ngrx.io/ https://ngrx.io/
- 6510 4y agoThe url is the state, everything happens in response to url changes and everything changes the url. Before I tried calling functionality and updating the url in response to user actions but since the state has to be exactly the same if you paste the url into the browser I got rid of the direct response.
- cheri9 4y ago[dead]
- gardenhedge 4y agoI'm the first to mention it: Remix run. No need for complicated state on the client.
- revskill 4y agoRedux Toolkit with Typescript is my choice for now.
- zenosmosis 4y agoI prefer sticking w/ the basics and using EventEmitter. https://speaker.app https://speaker.app has a UI I've been prototyping w/ this approach.
- manx 4y agoWhat is EventEmitter?
- samtho 4y agoIt’s Node.js’s event system. It has been backfilled ad-nauseam to the browser.
- imbnwa 4y agoYou ain't lyin https://www.npmjs.com/package/eventemitter2 https://www.npmjs.com/package/eventemitter2 https://www.npmjs.com/package/eventemitter3 https://www.npmjs.com/package/eventemitter3 https://www.npmjs.com/package/eventemitter4 https://www.npmjs.com/package/eventemitter4 https://www.npmjs.com/package/eventemitter5 https://www.npmjs.com/package/eventemitter5 https://www.npmjs.com/package/eventemitter6 https://www.npmjs.com/package/eventemitter6 https://www.npmjs.com/package/eventemitter7 https://www.npmjs.com/package/eventemitter7 https://www.npmjs.com/package/eventemitter8 https://www.npmjs.com/package/eventemitter8 https://www.npmjs.com/package/eventemitter9 https://www.npmjs.com/package/eventemitter9 https://www.npmjs.com/package/eventemitter10 https://www.npmjs.com/package/eventemitter10 https://www.npmjs.com/package/eventemitter11 https://www.npmjs.com/package/eventemitter11
- gabereiser 4y agoGood ol’ {} Add anything you want to keep to it, store it in the window with window.app = {} You can mix local storage in with it too if you want to write a class that checks its existence with a key. Why must state management need a complex solution? I’m sick of frameworks and modes where they abstract away the simplicity of javascript in favor of their way which is very economically driven.
- Ambolia 4y agoI assume the idea is for changes in the data to trigger changes in the UI? If you just keep the raw data on an object you still need an additional mechanism to synchronize the data on the screen.
- swagasaurus-rex 4y agoEncapsulate it into two functions: window.getState(); window.setState(); You could even use document.querySelectorAll() to go through all the elements on your page, and update them based off values in the state, whenever window.setState() is called. This is basically all front-end frameworks in a nutshell. You've invented reactive programming in the browser.
- tomduncalf 4y agoPerhaps my way of thinking is React-centric but this feels like a pretty inefficient way to do it. Feels a bit like reinventing the wheel poorly when things like MobX exist, sure it’s simple to start off but then you hit performance issues or issues with dependent state etc. etc. and you realise why, for all the derision they sometimes get, libraries exist to solve this problem and they are useful. But for a simple thing built with JS that isn’t going to need to scale to a large codebase or whatever, sure, keep it simple!
- Kiro 4y agoI build games where I run a global setState on the root component 60 times a second and even with deeply nested components it's not even a factor in performance.
- 7sigma 4y agoMore like a cache for back end data but it covers a lot of the use cases for front end state management. https://tanstack.com/query/v4 https://tanstack.com/query/v4
- david_p 4y agowe’re using ngrx. Context: the app in a large enterprise Angular app (100+kLOC)
- pookeh 4y agoMobx
- ulshv 4y agoMobx. Never looking back to any other React state management library
- whelton 4y ago+1 for Mobx. I use it in Conjure[0] after watching a talk about how it’s used extensively in Linear[1]. I love it. [0] https://conjure.so https://conjure.so [1] https://linear.app https://linear.app
- tomduncalf 4y agoIt was always MobX for me, I’ve built a few sites and React Native apps with it and found it extremely productive in exchange for some magic, but it could be seen as somewhat heavyweight compared to some more “modern” solutions. Jotai and Zustand are two that I want to investigate but not used them yet.
- frompdx 4y agoMy personal favorite is re-frame for ClojureScript. I have used it to build things like a LaTeX editor with live preview, electron app frontends, and web-apps. There are wrappers like Kee-frame that extend re-frame by linking the URLs query to the current state, making it possible for users to easily share URLs to different states of a single page app. The cons are: - A fair amount of work to make changes to the state side-effect free, but the documentation has a good tutorial on how to approach this. - It's for ClojureScript, so it's a non-starter for organizations that will not consider anything outside of the mainstream. I have also used Elm. If I recall correctly, Elm's state management paradigm was inspired by re-frame. I found writing JSON decoders in Elm to be demoralizing and tedious. Since the creator of the language was vehemently opposed to providing any real JSON support I decided to move to ClojureScript.
- ogoparootbbo 4y ago> Elm's state management paradigm was inspired by re-frame Nope, it's the other way around
- frompdx 4y agoDesigned in late 2014, it slightly pre-dates the official Elm Architecture, although thankfully we picked up foldp ideas from early Elm games https://day8.github.io/re-frame/re-frame/#why-should-you-care https://day8.github.io/re-frame/re-frame/#why-should-you-car...
- ogoparootbbo 4y agostated chronology doesn't imply inspiration
- blktiger 4y agoThus far I’ve really enjoyed https://xstate.js.org/ https://xstate.js.org/. It’s fantastic for ensuring that your application is in an expected state and to control transitions between states. When it’s overkill you can often just drop to useState for simple stuff.
- Veuxdo 4y agoI use the let keyword to store values that I know will change.
- Tade0 4y agoxState Sometimes you really need a state machine and for me this is the go to library. Pros: -Visualizer. Non-tech people love the visualizer. Tech people as well really. -Integrates easily with entities which are also implicitly state machines, like Promise. Cons: -Learning curve. I've already rewritten our state machine once because my original implementation was not idiomatic. Mobx also works. Ngrx, Redux and the like just smear your logic all over the place, which is bad.
- nathants 4y agoreagent. reacting to deeply nested maps of immutable data in a single location. this is the way.
- jrvarela56 4y agoOne cool thing about Reagent (forgot where I found the quote): Reagent benchmarks showed it was faster than vanilla React due to how Clojure uses immutable data structures. The React team used it as inspiration for a big refactor (not sure if that's in it already, think the quote I found was from ~2017-18)
- have_faith 4y agoReact specific but i’ve built a couple non-trivial applications with Recoil. I enjoy the ergonomics of it and building up a state graph. At its simplest it like a global version of useState which is really all you need, something you’re used to but happens to be shared. I prefer things that have simple primitives that can be composed into something complex. The documentation is good for describing what it does but not the best at easing you into it’s mental model.
- wotamRobin 4y agoPrincipal eng working with 3 teams on a ~500k loc React site here. After lots of experimentation, we’re just using React contexts. - Redux is cool but there’s so much decoupling that it gets hard to read the code. New hires would take too long to start, TS types got crazy, it was too much. - XState is very good for state machines… but you barely ever need that level of control. Most of the time understanding it ends up being overhead. We’ve had maybe one good case for using it in about 10 years. - React’s contexts are minimum overhead and work very well with “jump to definition” functionality and TS types. You can choose to use a reducer if you want, or skip it if it isn’t appropriate. YMMV of course. This is just us.
- shukantpal 4y agoWhat are your thoughts on MobX?
- aidos 4y agoWe use mobx and I think it’s great. The observable / computed model is really familiar from spreadsheets so it’s very easy to reason about code and computations. You always just think about your data in terms of being computed from dependencies without worrying about pushing state though the system. We have an object graph (updated via web socket subscriptions) and then twist and turn slices of that data on the way up to the components. I hardly think about the fact that mobx is there and instead just think in terms of reshaping data for display.
- ledauphin 4y agoi like mobx because it encourages you to separate state from presentation more than React Context does, but doesn't discourage keeping logically separate state trees separate the way Redux does.
- dcchuck 4y agoOther poster here - Success with MobX on a project. I worked as lead picking up an existing code base - none of us had any MobX experience so came in fresh. My employer was kind enough to offer up FrontendMasters subscriptions - I watched a MobX course there over a couple of nights - link: https://frontendmasters.com/courses/redux-mobx/ https://frontendmasters.com/courses/redux-mobx/ I enjoyed it! Got the job done, no scaling issues
- devmunchies 4y agoBeen building in HTMX for the last month and I’m loving the new paradigm. This vid did a good job of explaining the shift. https://youtu.be/LRrrxQXWdhI https://youtu.be/LRrrxQXWdhI (Been using preact/react since 2016, angular/jquery before that)
- primitivesuave 4y agoThanks for sharing this, I found this paradigm to be highly intuitive. Adding a link to the HTMX docs which also do a great job of explaining: https://htmx.org/ https://htmx.org/
- devmunchies 4y agoAdding: another reason I like it is the backend does the rendering (like server rendered react)[1] except the language doesn’t matter (agnostic) so that I’m able to use a functional language (F#) to build all my “components”. [1]: not actually like server rendered react, since srr only happens the first page load.
- fatih-erikli 4y agoseparate useState's for each piece of a global state, preserving it in a flat shape, no nested objects.
- brundolf 4y agoI try to stick with plain React hooks when I can. For small-medium state complexity they're usually enough For big stuff, especially deeply nested trees, MobX is still my favorite. It has some quirks but the core premise is such a simple and ergonomic mental model to work with, even for very complex state with intermediate derivations
- manx 4y agoWhat are the quirks?
- brundolf 4y ago1. It's an add-on, so eg. you have to manually wrap each React component in an observer(), it doesn't really interact with hooks (triggering or responding to updates), etc 2. It has some minor gotchas around object cloning, proxies, memory usage, and stuff like eg. certain functions have to be pure But in practice these aren't big barriers; once you get used to them they fade into the background. And I've made stuff with MobX that I'm not sure I could have built with any other state management system. It's also one of the best-performing ways to write React apps because it can be absolutely surgical about only re-rendering exactly the things that need to update, even moreso than the official state management system
- peterhunt 4y agoWhen you refer to frontend state management, I'm assuming you're talking about libraries like Redux, and are using something like React. Basically, storing state that cuts across the component hierarchy. First of all, I would suggest minimizing it as much as possible! You can often get away with a combination of component local state and data fetching libraries like SWR (the one I use) and react-query (I've heard it's good but haven't used). Modern data fetching libraries support intelligent caching, cache invalidation, and even optimistic updates. The vast majority of internal tools at Twitter (prev employer where we built internal tools) didn't need any state management at all outside of swr and component local state. However there will be some cases where some sort of client side state management will be useful. In these cases I reach for jotai. It was one of the first state management solutions designed post React Hooks, so it feels much more natural than state management solutions where hooks were bolted on. Additionally, it doesn't suffer from some of the rough edges that similar libraries like Recoil have (like naming fatigue from all those string keys). Btw, I only use a tiny subset of jotai. I don't use any of the persistence or async stuff. So tl;dr: 1. Build your app with component local state and SWR only. 2. If this gets messy, refactor your component local state and SWR code to be abstracted away as reusable functions / hooks. 3. Only when there is a performance problem or a really convoluted component hierarchy that doesn't make much logical sense, consider adopting jotai, but only for the parts of your app state that are causing the issues.
- JayStavis 4y agoreact-hooks-global-state which at this point is really just Zustand
- parf02 4y agoMy team is currently using this and I've been wondering if there are reasons to move to something like jotai or Zustand. The ergonomics of react-hooks-global-state with TS is quite nice already.
- JayStavis 4y agoAgreed! Haven't had the need myself but zustand probably makes more sense for a richer selector interface, using reducer syntax, etc.
- inopinatus 4y agoAssuming you mean a web-based application, then all state via HATEOAS, and CSS or JS in the front-end is strictly a non-essential progressive enhancement. This is for commercial reasons. Apps that depend on assets are crippled over low-bandwidth or otherwise unreliable connections, and frequently break in the presence of aggressive content blockers. I won't do that to my customers.
- jahewson 4y agoMy personal favourite is Zustand. But if you like proxy state then Valtio is really nice.
- h3rsko 4y agoJotai [1] is my go to, though I have never used it for anything too big. [1] https://jotai.org/ https://jotai.org/
- tuzemec 4y agoTrying Zustand for a mid-sized react project. So far pretty happy with it.
- Kiro 4y agoJust use a global object and continuously run setState on the root component inside a requestAnimationFrame. Whenever you need to use or display something just reference or set the global object and you will be sure it's visually updated within the next rAF.
- zenosmosis 4y agoI'm not sure if this was a serious comment, but that sounds like a massive amount of performance overhead. A way to optimize that approach substantially, while keeping everything else mostly the same, would be to have a setter on the global object, and only re-render the root component when that setter has updated the state. My suggestion is not a very optimal approach, but probably a lot better than the continuous state loop.
- Glench 4y agoSvelte with stores: https://svelte.dev/tutorial/writable-stores https://svelte.dev/tutorial/writable-stores
- dimmke 4y agoYes. This is the way. Once you use stores you realize how complicated state management was made. Redux in particular was so dogmatic about it. So much boilerplate. State is ephemeral. There’s no reason to need one global store.
- nextaccountic 4y agoIs this like React contexts? I can't find a comparison of them (when I google it, it finds comparisons between svelte store and svelte context)
- adamnemecek 4y agoI'm not too familiar with react but AFAIK contexts are a thing that you reach for only occasionally. Svelte stores are a fundamental concept. Check out svelte, it's amazing.
- surkov 4y ago[dead]
- kevinak 4y agoNo, Svelte stores don’t use effector under the hood, they’re most definitely hand written and aren’t using any dependencies at all.
- moklick 4y agoI think it depends if you are working on an app or on a library. In an app I would recommend to use Zustand or Jotai. If you prefer a Redux-like state management with a central store and actions to update it, go with Zustand, if you prefer a proxy-based atomic solution, go with Jotai. There might be situations in library code where it's useful to use React context but I would not use it in app code. It's too easy to use it wrong.
- jemmyw 4y agoAt my employer we have developed our own state management solution on top of react-easy-state. It's a good solution for us, it matches the backend more closely and has some conventions that work for our model. I wouldn't necessarily recommend it for other apps. For personal stuff I like recoil and jotai. They're similar in design. Super simple to start, easy to type, work with layers of complexity.
- fuzzythinker 4y agoI like valtio, works w/ React or just js. Has subscribe, derive, and more. https://github.com/pmndrs/valtio https://github.com/pmndrs/valtio
- schwartzworld 4y agoI have been a react dev for 7 years and have loudly advocated against state management tools all that time. React already is a state management tool, designed to eliminate the need for complex global state. You only need external state management if you don't fully commit to the paradigm.
- jamestimmins 4y agoCan you expand on what you mean by "the paradigm"?
- schwartzworld 4y agohttps://reactjs.org/docs/thinking-in-react.html https://reactjs.org/docs/thinking-in-react.html
- yawnr 4y agoSorry but what? What do you do when a parent component needs access to a particular slice of state? Refactor the entire tree? What about deeply nested components? Prop drill 100 levels deep?
- bobkazamakis 4y agoemit and observe an event with a callback passed down?
- 8n4vidtmkvmk 4y agoplease no. my work does this and the events are completely untraceable. you have no idea what's listening to what or where it will be caught or prevented
- eviledamame 4y agooof
- dbetteridge 4y agoreact-query to handle server updating state and per component hooks for local state items. react-query has hook wrappers that allow accessing data you've fetched once across multiple components. Calling the refetch in one will update all components using that data. It's clean and minimises the need to think about shared state
- parf02 4y agoThis. Along with a global state library of your choice for everything that is not server related data.
- lastofus 4y agoI've recently started working with React Query (now Tanstack Query since is supports Vue and others) and I absolutely love it. Coupled with a sprinkling of `useState` and context, I'm all set. Of all of the SPAs I've worked on, 90%+ of the "state" is just server side data, pulled down via APIs, to display to the user. Other state libs don't bother to take into account common things like cache invalidation, or loading states, but it's all built in to React Query.
- antigirl 4y agothis, hands down is the best solution. I was using Apollo initially for my graphQL needs and started using that for local state too, but moved to urQL as found Apollo bit slow and bloated. I love the loading/err/res conventions carried over to react-query.
- valand 4y agoSimilar to some strong sentiments in this thread, we don't use common state managements. Mainly because they doesn't suit our need and requires us to learn more unnecessary patterns. My company is building app with quite a set of complex features and structure (e.g. stateful integration with game consoles, background custom upload protocol, varying lifetime of modules, etc). - The state management we always come back to is closure-based objects. - Styled as agents, rather than passive storage (e.g. redux store-like construct). Thus providing separation of concern both in type definitions and code execution scheduling (can't find better words for these :')) - In house event utility is used by the agents to communicate outwards. - Combine with useEffect, useState, useMemo, and our in-house event utility to "escape" React's lifecycle by default and selectively subscribe to events, thus avoiding unnecessary-rerenders problems. - Designed to abstract its domain and expose its internal data via methods. - Optionally be designed to allow both code reuse and object reuse. Allowing devs to share or to not share states. Common use case for object reuse is agents acting as background-service propagated via React Context. It works really well with React Context. - Optionally self-managing via buffers and async loop. The buffer is not exposed to its consumer directly, and the async loop works on the buffer. - Can be useful for dependency injections too. - Well isolated and optionally injectable so that you can unit-test against it without import mocks. A caveat, this pattern isn't as usable when written with pure JavaScript. We relies heavily TS on FP patterns supported by fp-ts and io-ts as well as IDE's auto-complete and jsdoc to unload a whole stuff off our mind. We've sometimes evaluated common state management solution and often found them requiring us to remember more things, but it doesn't yield valuable abstraction. In fact, most state management is abstracting the wrong thing.
- nvegater 4y agoRecoil for single page apps. As simple as context but more readable. For another app the url was used as a single source of truth, so kind of a global state. The components just called useQueryParams. For multi page apps (e.g. with nextjs) I’ve never used a global state manager. Next-auth, useReducer and react query are enough until now.
- jwilber 4y agoSvelte stores.
- michaelchisari 4y agoFor 98% of projects? A global state object that gets passed down the component tree. This can scale to much greater complexity before it becomes an issue than many are willing to admit.
- SkyPuncher 4y agoI don't think people are concerned about the performance here. It just gets messy quickly. Most of the state management libraries allow you to avoid passing a value up and down the tree.
- farmin 4y agoAmen. I'm glad I'm not the only person that has resorted to this. I've done it on Angular too in the past. Just a core service that holds all the state, import it into everything.
- symlinkk 4y agoThen you are prop drilling. Most projects I work on have hundreds of components and that would get old fast.
- recursivedoubts 4y agohear me out on this: hypermedia as the engine of application state https://htmx.org/essays/hateoas/ https://htmx.org/essays/hateoas/
- AngriestLettuce 4y agoKeep it simple. Have global state where it needs to be global. The easiest way to avoid problems with multithreaded writes to globals is to not have multithreaded writes to globals. Ensure all writes to said global only occur in one thread. One possibility is to use e.g. locks and semaphores to ensure only one thread writes at a time, but nothing can beat the amazing synchronity that is imperative programming. Try it out some time. Tell your friends. The real secret here is that there are very few things that actually need to be globally writable. Most things that are global should be constant, so not a problem. For those which aren't, you probably have some kind of IPC message passing thing in your programming tool of choice. Use it to pass any state changes to global state to your main thread, which changes it. Be aware that race conditions may happen. If they cause you issues, make them not happen any more. Don't worry so much about life. There will be problems with every approach. Pick one with few problems, and deal with them as they come. Multithreaded programming is inherently complex. No need to make it worse than it is.
- parf02 4y agoI'm curious how you are doing multithreaded in the front-end. You're talking about modifying your global state from a web worker?
- AngriestLettuce 4y agoA front end is simply an application that talks to a different application to receive its data instead of processing it directly. It can be as threaded as you like.
- jrvarela56 4y agoThese are the options I have used and tested heavily (only in React): Redux: - pros: framework to place different pieces of logic, makes it predictable once everyone is onboarded; boilerplate (actions, reducers, selectors, etc) makes it easier to avoid mistakes if you're not using TS - cons: boilerplate adds a lot of friction that's not needed if you're using TS; debugging usually requires jumping through more files XState: - pros: what I said for Redux but on steroids - cons: big setup (learning-wise); feels overkill 95% of the time Context: - pros: simple to understand and use (you expose values and setters via useContext); minimal setup (Provider and useContext) - cons: you're still trapped inside React, your logic is inside a big component by default Mobx: - pros: keeps your logic out of React by default; you can export your model to another env and debug/test/play easily - cons: most costly to setup (learning, config) out of all the options (redux with starter toolkit reduces the setup overhead) I mainly use Context now as I port from Redux. Feeling the pain of not having an interactive model outside of my app views and want to get my team on Mobx.
- jrvarela56 4y agoIf you think this is convoluted or overly complex (I see a lot of 'just use Javascript and DOM APIs') think about it for a second: how many libraries do you load in your backend projects? We have a lot of dependencies related to state management (database, ORM, caching solution, task queue, etc) - it's a big problem. Why wouldn't we use tooling to make our lives easier in JS/TS frontends?
- doodlesdev 4y agoBecause the backend actually does something. Truth is 99% of frontends are just a way to display data just fetched from the server and don't really have a need for state management at all. For the 1% out there, use Redux (or Redux Toolkit), or maybe forget about React since it's not the only library ever invented.
- jrvarela56 4y agoHow would you develop a web app that needs to work offline?
- hellcow 4y agoMy native web components fetch their own state. They pass data to children via attributes and to parents via event bubbling. Very happy with this solution. Re-renders work using observableAttributes, which is part of the native component standard. It’s “just JavaScript” that everyone already understands and still avoids global state. But while some of the UI I build is complex, I don’t build SPAs. If I did maybe this wouldn’t work as well.
- desio 4y agoVue with VueRouter.
- dfbdns53463 4y agoAt work when I was on the front end side( our company uses Angular(honestly its dope, it should be more popular IMO) ) and we settled with ngrx(a redux clone), which was fine until I used react hooks & context for my own side projects. I work for a major airline so I guess ngrx is a nice to have for a multi page multi state SPA but seriously there is way to much boiler code with ngrx/redux.
- liximomo 4y ago[dead]
- Leimi 4y agoIn the react world, valtio is a breath of fresh air as it removes almost all boilerplate code.
- jerrygoyal 4y agoI can't recommend this sweet library (Valtio) enough, recently used this on a project and I'm never going back to redux/mobx/jatoi/zustland/context etc.
- thepasswordis 4y agoI like recoil.
- jasfi 4y agoRecoil. It works well, I was new to React and just use React state vars, but there's too much complexity that builds up over time. The app I'm building (https://inventai.xyz https://inventai.xyz) is non-trivial, especially the canvas. There hasn't been any cost or downside. Quick to learn and implement.
- halotrope 4y agoZustand is great: https://github.com/pmndrs/zustand https://github.com/pmndrs/zustand It gets out of the way in terms of boilerplate, has a good solution for avoiding unnecessary re-renders, has tooling for deep state updates without messy syntax (immer) and strikes an overall good balance between powerful and easy to use. Cons might be that it is a bit more obscure so people might have to learn it. Also the learning curve is a bit steep. YMMV
- jerrygoyal 4y agocheckout his newer library Valtio from the same author
- preya2k 4y agoZustand is great! It is tiny and flexible (it allows you to use Flux pattern – or not, depending on your preference). It's my go-to state management solution for new React projects.
- doodlesdev 4y agoSvelte. Simple and obvious global stores. When working with Flutter I like provider. With React I use Redux Toolkit, but saying I like it is a stretch.
- bhl 4y agomobx-state-tree (https://mobx-state-tree.js.org/ https://mobx-state-tree.js.org/) Benefits of it over mobx is data normalization with references and JSON patches which allow you sync complex state easily. Typed models are also a plus. Drawbacks are performance (see https://github.com/mobxjs/mobx-state-tree/issues/1267 https://github.com/mobxjs/mobx-state-tree/issues/1267). Previously was using immer, which I loved because of immutability but moved off since classes and OOP didn't feel as natural as in mst. If I were to pick an alternative, might try redux with normalization https://redux.js.org/usage/structuring-reducers/normalizing-state-shape https://redux.js.org/usage/structuring-reducers/normalizing-.... And if I were to build a state management tool, I would prioritize a library that has - immutability - JSON patches and snapshots - data normalization with references - schemas / models compatible with zod
- ralusek 4y agoI use this whenever I'm free to, and I was surprised it never caught on more.
- gtsop 4y agoI remember I didn't have any concerns with state management when I was using emberjs. not sure why. Now, working with react, I have successfully avoided redux and any extra state management like yhe plague. Good abstractions, hook factories (under-disscussed topic imho), some sparse contexts. So far it has worked out great. I recently managed to implement quite complex requirements using these disciplines on a project while some other part of the same project contains redux-hell to do some simpler things
- nailer 4y agoSvelte stores. Mainly because the docs are practical and not a lecture about state management or functional programming and secondly because stores come with Svelte. React seems to be drowning in its own complexity these days. As another poster points out you can do global state by observing an object on ‘window’, that most react state management tools make this more complex rather than simpler is concerning.
- austin-cheney 4y agoI use a simple 4 point system for state management: https://github.com/prettydiff/wisdom/blob/master/state_management.md https://github.com/prettydiff/wisdom/blob/master/state_manag... I use it for an OS GUI here which fully loads in 200ms in Chrome (300ms Edge): https://github.com/prettydiff/share-file-systems https://github.com/prettydiff/share-file-systems When simple things, like state management, become complicated they are either over engineered or poorly planned.
- gherkinnn 4y agoIn React: - Provided it is not an offline-first app, move as much state handling as possible out of the frontend - use SWR or React Query for server state - Keep pagination, filters, and other such options in your URL - Hold state as local as possible. Only ever move state up if two or more branches of the tree need to be synchronised. - Pass information down through props. That is what they are for. A little “prop drilling” is fine. - Use CSS custom properties for theming This gets you >95% of the way with very little complexity. For the leftover pieces of global state like ‘isSidebarVisible’ I like Zustand because it is tiny both in bytes and concept. I don’t like to use Context for state management because it litters the top-level with providers and causes unnecessary rerenders. Avoid a single global store at all costs.
- KronisLV 4y agoPersonally I have enjoyed Pinia the most when working with Vue projects: https://pinia.vuejs.org/ https://pinia.vuejs.org/ It is simple (no need for lots of boilerplate code), reasonably performant, integrates with the browser Vue dev tools nicely and is just generally a pleasure to work with, especially because Vue does a few things better than React in my eyes - most notably, the hooks. Pinia in particular also seems to generally get out of your way and doesn't enforce a particular architecture upon you. Want to add methods to the store to interact with an API and not have to think about that in your other components, merely call a method for initializing some data from the API that will take care of the store state? Sure! Want to do the opposite and only use the store for persisting data, regardless of where it's initialized? Go ahead. Want to have your components react to changes in the store? This will work with either approach. This is subjective, of course, but personally that combination of tools has resulted in a pretty good development experience, in my eyes something like the following is a nice stack: - Vue 3 with Composition API (hooks) - using SFC with <script setup> (takes care of some boilerplate) - using Pinia for state management - using PrimeVue or a similar component library (to have ready-made components for most needs) For React, I have to say that MobX was nice last I checked: https://mobx.js.org/README.html https://mobx.js.org/README.html though React's own Context functionality is also okay: https://reactjs.org/docs/context.html https://reactjs.org/docs/context.html
- amoerie 4y agoI've been working on a large React + Mobx codebase for nearly 3 years now, and it's still holding up surprisingly well. Mobx is really well designed and plays nicely with React. I haven't encountered anything more appealing than this combo yet (Admittedly I haven't tried Vue yet)
- djohnston 4y agoGlobal document object