r/reactjs • u/mikeour • May 14 '20
News Facebook has open sourced an experimental state management library for React called Recoil if anyone is interested.
https://recoiljs.org/40
u/JanF93 May 14 '20
That looks kinda nice to me. Seems also far less verbose than redux :)
20
u/Veranova May 14 '20
Well it doesn’t attempt to solve any of the same problems beyond being a global store, so really isn’t comparable. Like using context for everything it probably excels in small projects.
→ More replies (1)50
u/m-sterspace May 14 '20
I would disagree, it looks like it solves many of the same problems as Redux.
The primary problems that Redux solve are:
Single global state management location so that you have a predictable location for store actions, and so that you don't end up with spaghetti code
A backdoor / out of tree connection to components so that if a low level component is dependent on state and that state changes, only the low level component rerenders and not anything above it.
Debugging tools so that you can step your state forward and backwards as your application is running.
This seems like it has all of those, and the out of tree connection to components is quite frankly the single biggest benefit of Redux over the Context API.
34
u/darrenturn90 May 14 '20
The main problem with the hate that redux receives is that it’s been mostly used in the way you speak about it above - but that’s similar to buying adobe photoshop for you to change the brightness and contrast on your photos - sure it can do that, but you “probably don’t need redux” in that case.
Firstly the clue with redux being more should be in that it exists outside of and separate to react - you don’t need a react component nor do you even need react on the page to use redux itself. There is the connection package react-redux which ties it together - and this is often forgotten almost.
Secondly, the ability to inject functionality into the middle of a uni-directional pure process flow to handle asynchronous and other similar effects can not be overstated (and infact anything else too).
Third, the redux team have done a great job at covering off the vast majority of “complaints” with their redux starter kit work that provides plenty of helpers and assistance.
Now, this is not to take away from the library mentioned by the OP - I have a separate comment regarding that in this thread, but it’s like comparing apples and oranges - and the fact you can’t see that is partly why redux has gotten a bad rap all these years. It’s like trying to put a Car in your bicycle space - it won’t be pretty, but you can’t blame the car for being a car.
→ More replies (6)32
u/m-sterspace May 14 '20 edited May 14 '20
See the thing is, I think Redux is awesome. My applications have vastly improved since I started using it, and now that I've slogged through a lot of the learning process, I understand Redux's intent.
But I still think that Redux is not ideally documented for people first approaching it (it should be more opinionated imho), and not the best designed from an API standpoint. Part of my issue with Redux is that the api is not designed in a way that lets you start small, and grow. You basically have to understand all of Redux to even get started using it. Up until Redux Toolkit, there was no way of just getting quickly started with Redux. You'd have to learn a whole boat load of terminology and apis and plugins just to get to the point where you could code a basic to-do app. The toolkit is a big step in the right direction, but it still wants you to learn basically all of Redux just to be able to implement a simple state object.
Essentially, to me, Redux has always felt like they want you to be a mechanic when you all want to do is drive a car. The toolkit is getting a lot closer, but I'm still open to other people's idea of state management solutions. I'm not convinced the Redux API is the best possible way to do design an api that does everything Redux does. That being said, given how widespread Redux is, I would still expect it to remain the de facto standard, I just think there's always room to see how other people might approach the same ideas.
→ More replies (9)→ More replies (23)2
u/didled May 14 '20
Damn I’ve been using redux for months and I haven’t seen that good of an explanation yet
10
u/A-Type May 14 '20
This looks really nice! I'm a fan of the concept of a writable selector, and how the hook usage is identical to useState. This seems super easy to adopt.
I'm curious about the overlap with Context usage. Since part of the expressed intention is to share data across components, but the data stores are direct module references, not Context values. I've seen things moving in this direction since Suspense has started to take shape, I wonder if Context will become less utilized as the ecosystem moves more to simple module cache references with Suspense.
8
u/Nathanfenner May 15 '20
I'm curious about the overlap with Context usage. Since part of the expressed intention is to share data across components, but the data stores are direct module references, not Context values.
The store is still in Context; that's why you need to wrap in
<RecoilRoot />.When you do something like
import { fontSizeState } from './fontSizeState';you're not actually pulling the state from that module - you're just pulling the name of the state and its default value.
→ More replies (1)1
u/pobbly May 14 '20
This can be done without Context, just with hooks. Js itself provides us with everything needed to share state - closures and higher order functions.
I use a utility function 'createStore' that takes an initial state, sets it and an array of listeners in its scope, and returns a 'useStore' hook which uses useEffect to sub/unsub to the shared state in the outer scope. This higher-order hook has the same signature as useState. Call setState on one instance and others are updated. Works great and it can be trivially extended to use other persistence middlewares like localStorage.
7
u/KPABA May 15 '20
For the first time I can get 100% behind the features, style and philosophy of a state management lib that looks better than mobx. Well done
8
4
8
u/Awnry_Abe May 14 '20
Looks interesting. I don't care much for the selector syntax. Instead of { key: "foo", fn() }, { foo: fn() }
3
u/SeerUD May 14 '20
Aah, this looks really nice. Seems like it could be a simpler alternative if you're using Apollo to using the local state stuff. Seems really clean and simple.
3
u/gregmuellegger May 14 '20
The docs are incomplete yet, but this looks very promising and easy to use.
The useRecoilStateLoaded seems to be an elegant and standardised way of handling not yet resolved states from promises.
Looking forward to this maturing. The integration with state in urls seems also rather nice with little complexity, but couldn't find it in the docs.
2
3
3
May 18 '20
looks lame af, could these people forget about redux for a moment when creating a library please. What the point of a "new" library if this is just the same shit with some hook or whatever syntax that's the "dx" trend of the year.
2
u/deliciousmonster May 14 '20
reminds me of react-sweet-state by the atlassian team.
9
u/IllustriousEchidnas May 15 '20
Just given the number of FE state-management related bugs in JIRA, I'm not even going to open that link
2
u/BowlingX May 14 '20
Looks nice :) For URL handling I published something (remotely) similar that tackles the same problem with global state I faced in large e-commerce applications https://github.com/BowlingX/geschichte
2
u/zephimir May 15 '20 edited May 15 '20
Wow! It's so simple I love it! Looks a bit large though ? Thrice the size of redux although it does handle async directly which means no need for additional bits like thunk
2
u/dance2die May 15 '20
I used to use react-atom a bit awhile ago and the concept seems similar.
Would the recoil library also be based on Clojure script's Atom? (which I am not familiar with but react-atom uses libre-org/atom underneath the hood).
2
u/mmoubi May 15 '20
Compare to redux Recoil looks much more intuitive to me.
Working with global app state in a similar way we do local component state is something I wanted to see for quite some time 👍 Recoil seems to be born out of complex use cases, not just an ordinary website or blog.
Reminds me of this Erik Rasmussen's talk https://twitter.com/belgac/status/1260901450332418050 where he explains why React hooks are not a magic solution to all state problems.
Watching for sure...
2
u/ConfidentMushroom May 14 '20
Conceptually, looks very similar to observables and RxJs. Should be interesting to explore further.
2
u/sfvisser May 14 '20
Why would you want to tightly couple your components to a global piece of state? Why not just pass in state using props and keep your components pure, reusable and predictable?
8
u/BowlingX May 14 '20
You would still do that, to connect those components to the global state you would use a wrapper component that then uses the hook (or use HOCs) which populates your pure components props.
1
u/sfvisser May 15 '20
My point is you should not connect your components to a global state at all. The parent component decides what data gets in there, not the component itself, because that would break reusability. With parent component I don't mean an HOC in the same file, but the actual use site.
I've seen (and unfortunately inherited) a bunch of projects where the majority of the components pulled their own state from a global store. Try refactoring those so the components become reusable in a slightly different settings. It's a nightmare. All easily avoidable by just passing in state using props and not having the component (or it's one-to-one HOC wrapper) decide this for itself.
4
u/isakdev May 15 '20
Which is why I'm currently moving away from using useSelector back to good 'ol connect with map state/dispatch on export. I can test with enzyme by just passing props and reusability goes up by having pure unconnected components.
2
u/tomius May 15 '20
This reminds me a lot of what I've been doing for the past months, which is using RxJs to manage the state.
The syntax and functionality are very similar. I wonder if they are doing that under the hood.
It's been an absolute pleasure to work with, so I might try a not so homemade solution. Looks very nice.
2
May 15 '20
From what I've seen:
- cleaner syntax and less verbose than Redux
- I don't know if Mr. Zucc truly has learned something from the store structure of MobX, but this kinda reminded me of that, and that's good actually.
- Easier to understand and follow the flow of state management than Redux
So far this is good! I hope Facebook follow through with this. I am building a new React stack for my company, and judging from the state of Recoil, I think I'll consider ditching Redux and use this if the situation is fit.
4
u/acemarke May 15 '20
Just to check, have you looked at our official Redux Toolkit package? It's specifically designed to simplify most common Redux use cases.
Also, the Redux Style Guide has recommendations that should also lead to better patterns in your codebase as well.
4
May 15 '20
i still have some problems following the guide, but thanks anyway! I am still learning about Redux (have been working with it for just 4 months, and building our framework at the same time) so i guess i got rooms to improve :)
But my point still stands tho, I feel like i like the Recoil syntax better than Redux atm, maybe when i get a better understanding on the framework i'll change my mind :)
1
u/darrenturn90 May 14 '20
You can think of derived state as the output of passing state to a pure function that modifies the given state in some way
The example then uses a value from the module level scope inside the function get(textState) - which means the function isn’t pure - unless I’ve missed something obvious (which to be fair is likely)
Also it seems the selectors are deeply coupled with the individual atoms they work on - and can’t be interchanged or necessarily combined ?
Personally I prefer a flux architecture style myself (not redux but that kind of pattern) - but other excellent options are out there like react easy state (I believe?) that use proxies - I don’t really see what recoil offers that hasn’t been done more comprehensively elsewhere. I was expecting as it was from Facebook that it would leverage some internal react magic in some way but don’t see anything of the sort.
5
u/Nathanfenner May 15 '20
The
textStatevalue doesn't actually hold the state, it's just the name of the state (and also the default value to initialize it). The actual state is in a store inside the<RecoilRoot />which provides it to children with context.In other words, there's no side-effects that affect application logic when you're building/using selectors - the only side effect is building the subscription graph, which doesn't affect the resulting value, only when Recoil decides to rerender your components.
Also it seems the selectors are deeply coupled with the individual atoms they work on - and can’t be interchanged or necessarily combined ?
Since everything has a unique name, the idea seems to be that selectors should be meaningful on their own, but that meaning keeps them tied intrinsically to other bits of state.
I think this makes sense - selectors are mostly for optimization - you don't usually need to have them; in almost all cases, you can just compute stuff in render. Once you've measured and found that something is actually slow, you can define and pull out a selector that makes things fast again (or, alternatively, when you're constrained by the rules of hooks).
I was expecting as it was from Facebook that it would leverage some internal react magic in some way but don’t see anything of the sort.
I like that it doesn't - because it doesn't need access to any of React's internals, it's easy to understand and use. It's a natural pattern on top of what React already provides, instead of trying to shoehorn an entirely different model that doesn't quite work.
1
u/bestjaegerpilot May 15 '20
I get it, Recoil !== Redux but what about React.Context?
In the old days, the pain point with Redux was the boilerplate (hear good things now about Redux in that end)
The main drawback is the super opinionated API. For complex apps, this is a plus. But for everything else, it's overkill.
So in my current job, we switched to React Context
My take on Context is that:
it can be tricky to use to get performance right---cough, cough, for example, you need _two_ Contexts, one for state, and another for the setters.
the lack of opinionated API meant developer velocity was high but so was techdebt---because everyone implemented Contexts their own way
working with SSR is super tricky because the initial render doesn't see state updates.
So is this facebook saying that React.Context was a dumb idea? Not enough balance between adhoc and opinionated? Not performant enough?
7
u/brianvaughn React core team May 15 '20
So is this facebook saying that React.Context was a dumb idea? Not enough balance between adhoc and opinionated? Not performant enough?
No.
The React team has ideas for continuing to improve the context API. You can find some PRs and issues with discussions of this in the reoo if you poke around enough.
Recoil was created by a Facebook engineer, not the React team. If you think it looks compelling and want to use it- great! Go for it!
2
u/davidmccaberecoil May 15 '20
Facebook isn't saying anything -- this is just an experimental project, nothing official.
1
u/mat-sz May 15 '20
Feels refreshing to see something like this coming directly from Facebook themselves. I'm excited to try this out for my future projects, even if it's experimental software.
1
u/jacobp100 May 15 '20
It looks incredibly well thought out. Aside from style and verbosity aspects of redux, it solves two important issues (for me at least)
Separate redux reducers can’t use other reducers state, making separation impossible sometimes
useSelector/connect work on referential equality, which makes it hard to abstract away selectors that do stuff like map and filter
Also I’m excited the built in async stuff. Async is really bad in redux - understandable as it’s built around being synchronous. If the async stuff in recoil is as well thought out as the rest, it’ll be awesome!
Side note, can the values of atoms also contain atoms? In the talk there’s an atom that’s an array of ids, and a memoized function that takes an id and returns an atom. But then if you delete ids, you how have caching issues. What if you just had the array of ids be an array of atoms?
1
u/Andrew199617 May 16 '20
This looks nice i had to accomplish the exact same thing in my project and created a Event system. I listen to changes to an event and update state when the event changes. This looks cleaner than what i had implemented although there are some benefits to having an event being called. Recoil seems to be limited to only updating state on change while you can do anything you want with an event.
1
u/manscap May 16 '20
It really looks like facebook is going to deprecate class components. Everything coming out for react including Recoil seems to be geared for functional exclusively.
As someone using class based only in projects, I'm sticking with mobx. If it aint broke dont fix it
1
u/__app_dev__ May 19 '20
I just created a simple online demo for it:
https://awesome-web-react.js.org/examples/state-management/react-recoil.htm
This demo hosts all files from a CDN so you can view JSX code directly in the browser (a JSX browser-based compiler is used).
The same demo is also available for Redux, Flux, and basic React Hooks. See links for each demo from the main page.
1
u/ttamimi May 14 '20
Potentially stupid question: Can I (and should I) store something like a JWT token using this? (Instead of localStorage)
6
-3
u/kingdomcome50 May 14 '20
I can’t see any reason to use this over something like mobx.
Why do front-end libraries (specifically react plugins) always seem to target the lowest common denominator? (This is rhetorical, I know the answer) If you can’t grasp OOP or observables go find another vocation.
It sounds harsh, but having our tooling slowly but surely diverge further and further from what’s actually happening by glossing over the problem with more and more “magic” and dogma is so... so tiresome.
I can’t wait until the next library comes along to fix the obvious problem this library is going to create with the promise of “consolidating global state in one place!”
2
u/manscap May 16 '20
I don't know why you're getting downvoted except maybe by people that haven't tried mobx.
1
u/jacobp100 May 15 '20
Doesn’t mobx have more ‘magic’ than this? If you gotta use a proxy for your api to work, it’s going to be doing a lot behind the scenes
Btw, the shift away from OOP isn’t about making it easier for beginners. There are good reasons to not use it (just as there are good reasons to use it)
2
u/molszanski May 30 '20
‘magic’ than this? If you gotta use a proxy for your api to work, it’s going to be doing a lot behind the scenes
One of the most advanced and rock solid peaces of software we have are SQL databases.
You send
Select * from books b inner join authors a using (author_id) where a.age > 50 and b.price > 100to a database holding gazillion terrabytes of data and get a response in 1 nanosecond.It can use Proxisies, it can use GOTO it can use magic dust or whatever the fuck it needs to make that awesomeness happen.
And we should be grateful for that magic
1
u/jacobp100 May 30 '20
I don’t have issues with magic! I’m just saying mobx has complexity too—and not saying it’s bad for that either
→ More replies (1)2
u/kingdomcome50 May 15 '20
`Proxy` is a standard built-in JS object. The fact that you are aware of it's existence means there is no "magic".
Contrast this with the "core concepts" (a pretty generous description) section of Recoil. It's basically "hey memorize a couple functions and you are on your way!" It's dogma, not concepts.
FWIW _many_ libraries do this in an attempt to simplify via obfuscation -- Redux is a particularly well-known violator as well with its "actions" and "reducers" nonsense.
There are worse things to opine about, but "state management", as a discipline, has been solved (for any pedestrian use-case) for over 30 years. Having every library come along claiming to "improve" on this stuff by offering us a snappier API is... like I said... tiresome.
The truth is that the goal isn't to "improve state management", rather, to dumb it down so a code monkey can iterate on a project without an understanding of what's happening.
I'm all for reducing boilerplate and simplifying APIs, but there _is_ a trade-off. This library and it's "distributed state by design" is going to lead to a hell that only the next library can fix! And so the pendulum swings...
1
u/molszanski May 30 '20
If you can’t grasp OOP or observables go find another vocation.
Of course they can. Look at that
TodoItemcode. 2 pages of code to flip anisDoneswitch. It is not trivial to understand.2
u/kingdomcome50 May 31 '20
I haven't had the need to look at their docs in a while but I can assure you that any complexity is a result of the inherent complexity from the example chosen, not from the library itself.
The paradigm that Mobx offers is the absolute simplest state management solution fathomable. You literally just define your state (classes with annotations on properties that should trigger re-renders), inject them into your react tree, and then... use them. It's about as close as you can get to abstracting away state management. Are there some caveats? Of course, but it also doesn't claim to be a perfect abstraction.
Having developed react applications since 15.0 and trying my hand at a number of "state management" libraries (including rolling my own in the early days...), I cannot imagine someone using Mobx and then feeling like they needed to reach for something else.
The application I've been developing for the last few months is both rather complex and marshals MBs of data (so efficiency isn't something I can ignore), and I have wasted almost no time fiddling with the "plumbing" so to speak. The only time I think about my state is when I am synthesizing the data structures that define it. No bullshit.
0
0
u/bassta May 14 '20
It's like they are reinventing the wheel again. VueJS observables / computed , Rxjs, sweet state to name a few... And again this Facebook naming conventions like atoms and selectors that sounds awkward and out of place. Even the mobile site have terrible UX with empty main menu on top left and what you would expect to be in the main menu in bottom right . But people will jump on this bandwagon because it's coming from Facebook
8
u/crazyfreak316 May 14 '20
Even the mobile site have terrible UX with empty main menu on top left and what you would expect to be in the main menu in bottom right . But people will jump on this bandwagon because it's coming from Facebook
It says 'experimental'. I'm pretty sure it implies that the library and related resources will be rough. Also it's by facebook doesn't mean it's a huge library with a big team behind it. This library has 6 contributors with majority of commits coming from 3 devs.
1
u/davidmccaberecoil May 15 '20
Yep, this is being released in a VERY early state and we have a lot of stuff to fix up. It's mostly me and one other person, and our day job is shipping apps. We've worked with the React team to make sure what we're doing is compatible with the directions they're taking, but this is in no way an official FB project like React and Relay.
1
0
0
u/ilostmyfirstuser May 15 '20
would someone smart explain to me how to server-side render with this instead of redux?
1
u/davidmccaberecoil May 15 '20
The `RecoilRoot` component takes a prop called `initializeState` that you can use to set the atom state that will be used for the initial render.
1
u/ilostmyfirstuser May 15 '20
I love you. That’s what I thought when I read the doc but wasn’t sure.
How would this work with renderToString / hydrate from react-don/server? Just the normal pattern that we use with react-redux Provider?
0
May 14 '20
[deleted]
13
6
u/Seankps May 14 '20
Context never filled that void for you?
0
May 14 '20
[deleted]
4
u/ibopm May 15 '20
Serious question here, but what's wrong with having more contexts?
4
u/gunnnnii May 15 '20
The problem is when you're unsure how many components need a provider, there is just no good way to control it dynamically(since you need to add a node at an arbitrary place up the tree depending on a child node further down). And even if you figure that out, you've now coupled two nodes with an arbitrary distance between each other.
https://youtu.be/fb3cOMFkEzs?t=240
The author of the library explains the problem pretty well at around the 4 minute mark.1
u/Seankps May 15 '20 edited May 15 '20
I certainly understand the problems with context - mainly that it isn't meant necessarily for State Management and needs to kind of be adapted for that. But how is a subscription different then simply doing usecontext on one piece of your state? Maybe it's made easier by the fact that I always keep my contexts providers as classes so the state doesn't independently updated object..?
1
0
May 14 '20
[deleted]
5
u/cyniko May 15 '20
It's been used in production on internal tools @ facebook for years according to one of the authors. It just got released to open source today basically, if it gets positive reception, I'm sure it will get more momentum.
41
u/mikeour May 14 '20 edited May 14 '20
Here is the repo and if you want to jump straight to the Getting Started to see how it compares to other state management options.
EDIT: And here's an awesome video from the library author explaining a bit more about Recoil from today's React Europe livestream: https://www.youtube.com/watch?v=_ISAA_Jt9kI.