Legend: The Ultimate React State Manager?
Vložit
- čas přidán 9. 07. 2024
- Is Legend the perfect React state manager. Could be with an easy to use Proxy API that supports reactive observation and computed values, along with preact-signals style fine grained updating, in a package that is only 3Kb!
👉 Upcoming NextJS course: pronextjs.dev
👉 Code: github.com/jherr/legend-state...
👉 I'm a host on the React Round-Up podcast: devchat.tv/podcasts/react-rou...
👉 Don't forget to subscribe to this channel for more updates: bit.ly/2E7drfJ
👉 Discord server signup: / discord
👉 VS Code theme and font? Night Wolf [black] and Operator Mono
👉 Terminal Theme and font? oh-my-posh with powerlevel10k_rainbow and SpaceMono NF
0:00 Introduction
1:04 Local State With Legend
7:11 Context State With Legend
9:43 Global State With Legend
11:36 Outroduction - Věda a technologie
"How cool is that?" I love the way he keeps having fun with programming besides years of experience
That's why I'm still in it, cool new stuff every freaking day.
I am using use same phrase to motivate myself whenever I got bored :) Thanks to Jack
@@jherr Love it Jack!
@@jherrsome hate the non-stop learning; I love it!
programming is fun! I go for 40 this year, programming since 14 approx, more as hobbie than a job. Besides that, I have to say latest 10 years I think, is even funnier, because you have new amazing things to try out every day, when I started I remember we were very limited for a lot of things, hardware, network.... But today is like there is no limit, you can do whatever you want, in the way you want. How cool is that? ha
Started using this in production ~10 months ago and have absolutely loved this library. Simple, fast, and intuitive.
Thank you Jack for sharing these goodies with us. Would you consider doing a Part B kind of deep-dive to these kind of videos where you would go into into the codebase and uncover how they’re doing it? You did something a bit similar when you showed how to implement a state manager using refs+context ala zustand - I really enjoyed that one.
Thank you again!
That would be very interesting
Without having used in production or any projects, I can't say with certainty how it is, if there's any bugs, etc, but for what I've seen, it's easily my favorite implementation of state management. I think using get and set is so smart. It makes it very explicit and takes some of the magic away that, for example, solidjs has in its state management.
Finally an easy to google library name
Hahahah true!
Thanks Jack !! It's the topic which i found out recently and its so AWESOME.. i was looking for something like this . Thankyou once again, each day i learn more cause of you. :)
I really love how you blur out some parts of the editor to show the code you are explaining. Wonderful 😍😍
Your enthusiasm is infectious. Thanks for the informative videos. 🎉
Thank you so much for showing this. Much helpful.
Glad my message sparked your interest for it! 😁
Great video like always👏
It did, thank you! Sorry I didn't give you a specific shout-out.
@@jherr No worries at all, I'm just glad you made a video about it since I don't think many people have heard about it :D
Hi Jack, I wanted to thank you for your videos, especially "React State Management - Intermediate JavaScript Course" you uploaded 8 month ago, it helped me land my first React job, how cool is that! I was on the verge of a burnout at my company because of bad coding standards and bad management... and your video pushed me to learn React and break the cycle, now i can't wait to start my new job in September! ! Thank you very much!!
That's awesome! Good work!
Looks awesome! thanks for a great video!
Fine-grained reactivity and useComputed reminds me of how state works in Vue out of the box.
I think it makes sense that state changes should be isolated, as against React's default where every state in the component tree is reset when one changes.
Great content as always ❤
Nice video as always! ❤ Eventhough this looks really nice for react, as someone who also works a lot in Vue i feel like im watching something thats still not even close to the simplicity and effectiveness of ref reactive and computed in vue
Exactly!
The HOC observer reminds me of MobX, which I think looks better when getting and setting values in components, but requires more setup in the data store than Legend seems to. I guess every state manager has to have some kind of tradeoff when interfacing with react...
Edit: just heard the mobx comparison at the end :D
I just wroted the same. 😀
Thanks Jack, this is really cool
You are creating great content Jack!
Thank you for all your efforts!
Really appriciate!
I think that this might be the best all-in-one performant state management library that the React ecosystem has seen in a long time. The fine-grained reactivity and observable model hit all of the recent advancements in web UI performance perfectly. The ability to drop into their React SDK and/or keep the state global is amazing as well. I think that Legend will become the new legend in the ecosystem way faster than most have. The last thing they need to add is a data fetching and caching paradigm for async and server state.
I don't think they should add `data fetching` and `caching`. They should focus on what they do well. Manage state. If you need `data fetching`, add `react-query` to the project and use `onSuccess` to push data to the state manager. That's what I would personally do. What do you think?
@@franciscokloganbAgreed, maybe make some adapters for react query like jotai has.
Thanks Jack for Awesome video !!! Because of these videos it's easy to keep track or latest trend. By the way my favorite is Nano Stores 😊
nano-stores is great stuff too! Love the cross-platform support.
Why I'm getting this video after 9 months?! Even though I subscribed a while back.
I'm not in love with it - between the HOCs and other "gotchas" where things simply don't work because you may have forgotten to set something up just right is a huge "nope" from me. Thanks for demoing this!
Yeah having to wrap every component to make this work puts me majorly off. So if I ever have to wrap a component for any other reason I'm doing 2 levels of wrapping? Feels ick.
Imagine the never ending wrapping abbomination:
const Wrapped = connect(mapStateToProps)(injectIntl(observer(Comp)))
Seems that HOC isn't needed anymore, look at the React specific docs
how did you select/highlight the text you were showing and talking about?
am i the only one getting some MobX vibes here?? it looks great and i like this observables! awesome! Thanks Jack!
I started using this library a few days ago in a Expo/RN app, i was wondering if I'd see you make a video about it in the future 😄 love your content !
How do you find it so far?
Does direct manipulation work in RN just fine? I assumed it might use some web only features where I assume that they should support setNativeProps for this
Great vid! Will definately check this Legend out. Question: What's the benchmark tool/service with tables you show in this video?
This library is insane. It is much less constrained than Valtio and much less confusing. The docs need improving tho, seem to contain a lot of outdated stuff.
valtio is saddly buggy as hell
This looks pretty great to be honest!
Maybe a bit clunky to use with the observers and .get() everywhere though. I'd only use it for some high-frequency or otherwise heavy rendering. Still, it definitely has its place. Might not need to go for vue or some other signal-based library to make games anymore. I've tried vue once and really enjoyed the magical feeling of global state that Just Works™. This might not just work (you still need the observable HOC and .get and all that), but it's the closest I've seen a library get to just having a plain global object be fully reactive. Don't see any good use for it right now, but I'll keep it in mind next time I feel like making a game.
haven't used Vue but Svelte's state management remains something I majorly miss in React
Want to try it soon, currently using rtk & rtkq, but I think this with react query will be more fun to use
damn, first I learn redux toolkit, then zustand, now this, so much info
I've just watch Jack's video about Zustand and now this. I'm new to Nextjs 13, which one should I use?😂
You should revisit this library, 2 days after thia video was posted the team changed the API and its a lot better. You dont need to wrap components in observable anymore.
Also you didnt show it in this video but it actually supports next app dir / react server components really well, similar to your zustand in next app video but has fewer limitations
Nice! Thanks for the heads up! It’s kind of the way of videos like this that the APIs inevitably move on. Which is a good thing of course. Hopefully this video will still get it some attention.
@@jherr We'd actually been working on the new API for a while but finally got to updating the docs to encourage simpler APIs. Most things in this video are still valid ways to use it :).
@@jherr I watched it, but was quite confused - I had recently read the article about the updated version of Legend State, and it basically looks like Solid moved into React! all that refactoring should be totally unnecessary now - it's far more ergonomic, and this video likely doesn't do it justice anymore.
@@RasmusSchultz He changed the API on me the week after this video dropped. :( I'm reaching back out to see if it's stable enough to do another video then I'll unlist this video. FWIW, I wouldn't be the farm on signals in React. They are usually pretty limited. The big React speedup is going to come from React Forget in 2024-25.
@@jherr I actually don't care about speed - React as such is "fast enough", but native state management performance generally breaks down in larger applications from very simple and non-obvious mistakes, such as neglecting to memoize, and once you learn to memoize everything, readability suffers drastically. Most larger React apps are mostly noise because of all these subtle performance issues. I'm interested in Solid-style state management for the sake of simplicity, ergonomics, and (rather than performance as such) avoiding the most detrimental performance pitfalls. If larger React projects weren't doing redundant updates, the fact that it's still diffing individual components is probably a very minor performance concern for most projects, save perhaps really critical real time UI.
One thing with these state management libraries, like MobX and Legend, are all of these extra rules like enabling the global mode to get direct access vs wrapping with observer - it's like the rule of hooks. It's something you should know as the docs (rtfm!) of the lib you are using, but it introduces extra cognitive overhead when debugging these states. Additionally I would expect using Legend to suffer from "what is the right way" traps, where someone more junior blindly copy pastes patterns from elsewhere in the app or the internet, not fully understanding when and why to switch between the afforded patterns; this later, more subtle, pitfall is mitigated by having an opinionated library that provides guardrails via types or helpful runtime errors that will link back to docs or be self explanatory.
I do see the value here - as direct value access and modelling can be simplified with these trade offs, similar to mobx - just need to know when it's an appropriate time to use the knife to cut.
Great vid jack, thanks for the find! Definitely looks full featured and the perf is 😍
What framework or opinionated library provides runtime errors that link back to docs or are self explanatory?
How does this compare to Valtio and MobX? It looks to implement some similar ways of handling state.
Hey Jack, I like the new dimming you're using to draw attention to the code you're talking about! Really easy to follow.
I do think you could dial back the opacity of that mask by like 50% and still achieve the same effect while maintaining the readability of the surrounding code. The surrounding context is helpful and I had to strain a bit on this one.
Great video as always, can't wait to try this out!
Thanks for the feedback.
Thanks Jack, would it be possible to extend this video at some point on your take for persisting global state - hard to find a robust pattern that doesn't show flashes of dummy data (localStorage) - would a persisted store via @vercel/kv (redis) or something else provide an alternative to using localStorage or would this introduce unnecessary latency?
Have u worked with persistence? If u do, would u share me a use case?
I think they are using some signal kind of pattern so please can you make part 2 for exploring it’s internals
Hey Jack, Thank you for awesome videos. I knew your channel when you first posted Micro frontends topic. I wonder if micro frontends is the thing of the past because I do not see any more videos about it recently on your channel.
Oh no, it's definitely very much still a thing. I just need to get back to putting up videos on it. There is just so much stuff going on.
i highly prefer useSelector api which wasn/t mentioned in the video. adding observer HoC seems like so easy to forget and mess up during refactoring. also in the context part 9:11 Name is not wrapped with observer but First is, not sure if its a mistake or intended.
Name is updated using fine grained updating, which doesn't require the observer. First and Last are updating using React re-renders, so they require an observer.
Would you recommend this for production? You other video ranking state managers, you ranked try to use none, useState, RQ, Zustand. With Legend, where would it land?
I'm not sure if I would use it in a commercial project today. But I would trust it for a personal project.
The library looks really interesting and as usual your work shines Jack. Two questions though:
- Does it do "true" reactivity a la solid.js? Or does it throw stuff on the global window and let none be the wiser? I suspect that the core observable and computed do exactly that, but I am not sure
- Just for kicks and giggles, does it work with react server components? :)
According to the NextJS and React teams you should NOT use a state manager with RSCs in any case. You could use it as globals. But as folks will point out you aren't insulated from cross-request contamination if you use globals. So... I just wouldn't use a state manager with RSCs.
As for the globals on the window? Not sure what you mean by that. Apparently it uses a fine grain mechanism similar to preact-signals. That being said, if you want fine grained use Solid or Svelte (or the coming Vue Vapor). Those are the real deal for sure.
@@jherr Do they mean that we shouldn't build an Cart app with Zustand? I've just watch your video of that.😅 Sorry I'm new to Nextjs13.
@@kennyng1238 Zustand is great, this state manager is also awesome. Have a look and see what suits your needs better.
Honestly though, state management with the NextJS App Router is a tricky beast. You should only use state managers in client components, and even then I would hold off until I really needed them. Best to keep it simple and stick with React state and context.
@@jherr yeah this causes a lot of confusion
What extension do you use for checking visual re rendering issues in react ?.i need that
Just React devtools.
@@jherr oh i was wondering it might be different thanks
This looks great. Reactivity like Vue 👍🏾
Is this anything more than syntactic sugar with react state, still using immutable objects behind the scenes?
My guess is either they are using `useSyncExternalStore` or they have a subscriber with a simple piece of state they bump on any change. You have to use one of those to get React to re-render based on state changes (unless you are using the fine grained reactivity).
Seems neat. How well does this play with types?
For a proxy based manager, really good, actually. In order to get the `get` and `set` typed correctly you have to create a new synthetic type from the original object, that's not an easy trick.
Jack covers it. It is time to give some attentions to this library. What do you think compared to Jotai?
The ultimate state manager for me is zedux, hope jack will cover it someday 😄
Legend-State look like solidjs, react ecosystem has so much new thing recently, there all about performance. Mybe we can use react with near validjs performance in the near future.
Similar principles, but there's no way anything built on top of React will get anywhere close to Solid.js. You don't use React for its speed, you use it because so does everyone else.
Another state manager? But I'm tired, boss.
I haven't covered one in months!🤣
Looks cool ❤ My thoughts: If I was willing to wrap my component in observable, I would just use MobX 🌹
Is that how u really code? u keep making components even for 20 lines of code like for first name and last name ?
Hello Jack, If I were to compare this with zustand and recoil, how good is this since it is granular?
Also LMAO, it feels like it stole something from Angular RxJS to certain extent...
To me it feels slightly more comprehensible than Jotai. I think a very large Jotai tree could get pretty tough to work through. And I think it's less boiler-platey than Zustand. Which is funny since Zustand is way less boiler-platey than Redux.
In next.js it works poorly example of the observableFetch method which gives a hydration error
Valtio is best of all of them..I love it's simplicity
This is so much better than Valtio!
Tell me - I am using Redux toolkit avoiding React Query for GSM ... Am I wrong?
I wouldn't use Redux Toolkit and RQ in the same project, that's duplication of effort. RTK has a lot of the features of RQ alreay.
The thumbnail gave me PTSD lol
You're welcome!
That's a funny thumbnail lol
Would be interesting to compare it to mobx
valio still my favorite
a little bit more work than Jotai/Zustand however what it does is AMAZING wth!
The HOC-like pattern of wrapping components in observers feels a bit icky and backwards to me. If it wasn't for that, I'd probably use it.
useExternalStore hook seems to make these 3rd party state manager obsolete. Am I missing something?
If you want to write your own pub/sub then sure. But I think a lot of folks want something off the shelf.
Hi Jack Herrington, I'm a very big fan of yours. I like your content, they are very informative and inspirational.
I just want to ask if do you mentoring/coaching?
I'm a mid level self-taught Reactjs developer and would like to improve my knowledge with your guidance.
I believe I could learn a lot of things from you in a month compared to me doing self-studies in several months.
I would love to hear from you.
No, I don't do any one-on-one mentoring at the moment. My schedule is fully booked with content creation and everything else I've got going on. Thanks for asking though.
However, if there is a particular career question that interests you, then I might make a video on that if you post your question here or on the Discord server.
@@jherr okay got it. I'm happy you responded. Yes, I'll be joining up the discord. Thank you and more power to you Jack Herrington.
It uses className$ ?
Guess I'll have to add it to Tailwind CSS: Class Attributes in vs code settings
to have auto completion, sorting and color visualisation with it (using prettier)
I realy wish this settings would have the ability to be wildcarded like **className**
how does this stands up against zustand?
Faster, smaller, but with less adoption, currently.
the problem of react is not just a management of state.
Only thing I am not a fan of is having to wrap the component.
But i'm sure you could also do export default observer(Local) right?
I guess it's the same as exporting default memo(Local)
Hi , Can you make some content about “legend state + xstate” ?
Definitely some big updates to xstate lately that are worthy of a video. Not sure I would bring legend into it tho.
It feels like a little bit of a lighter version of mobx. 😮
why simply not use rxjs ?
Jack, I’m going to try this one for my current project. Thanks for the recommendation!
Jack this looks like vue with extra steps hehe
jokes aside, this is actually really neat. I get best of both worlds!
czcams.com/video/mellBc0hTBA/video.html
Is this sort of what solidjs does?
Kinda. Solid is a much more comprehensive implementation that isn't a hack. The only thing you can use the fine grained reactivity for here is to change the text content. In Solid you can drive anything in the DOM with signals (and really anything at all)
I'm worried about this implementation of Context. Isnt this causing rerenders in other components who use any of the parts of it? This is a known issue with context, no granular selectors there.
No. Because it’s the observer that is triggering the re-render and that’s in the leaf node.
Thanks
Wait, what?! So what is updating the DOM?? Legend lib???
Yeah, the fine grained updating is just updating the DOM, boom. It doesn't work for anything but inner text and numbers. So it's not a Solid by any stretech. But, if you have a need for speed then, boom.
Legend vs zustand?
Why so many state management libraries why not just use sveltekit or solidjs signals
😊felt like tailwind of Redux …. I don’t know 🤷🏼♂️ ,
When a React signals library was published (from the developers of Preact) allowing the use of signals in React, Dan Abramov issued a tweet that using functionality like singals is like knowingly getting rid of the manufacturer's warranty on the device in use. The design and philosophy of the current React at its core does not go along with signals, and such solutions should not be used in production applications.
And this $ (dollar) syntax look's like someone is trying to copy svelte way of iteractivity into React. Funny ;D
i think its a convention for observable, from rx community
I don't believe signals are ready for prime time. I read something recently about some issues with it.
Do you have a reference to the article? I'd love to read up on whatever doubts folks have about signals.
is this vue?
Nope, React.
Nice video! Cant help but question at what point do we just accept React needs to go if all we keep doing is papering over its deficiencies
time to leave zustand I guess because less rerenders -> faster apps?
I am kinda weird man I run behind black boxes
I think in the vast majority of use cases, you're not going to notice the difference. Zustand and Jotai are phenomenal 👍
Likewise, I always chase performance which makes me lose consistency throughout my React stack due to adopting shiny libraries. Somehow these black boxes make me admire Angular
Looks like a very leaky abstraction. Would have a hard time selling this one
Jack, is your company hiring? its rough in this market and I need a position. 8.5 years of xp.
I'm doing full time content creation at the moment. So, no. Sorry about that.
@@jherr smart!
This philosophy is extracted from MobX... however, MobX was fast.
MobX still is very fast.
The problem is not useState...
The problem is useEffect!
:) In the case of legend I think for an effect you would use a `when`. So when a value changes you would do whatever you want based on that change. I think you can also add a trigger function as well, so you can get called only when the trigger function is true.
Is this just mobx?
I'd use anything but redux tbh
Is it really that bad?
Yeah
Same, but it's just sad that most jobs require u to use it
Use the redux/toolkt for sure if you are going to do the redux thing.
Just use solid instead?
ecosystem I guess, same for svelte (the js ecosystem doesn't provide the same DX), otherwise no one would be using react for new projects
@@heroe1486 with solid you have everything to build production apps (ui libraries, testing tools, storybook, CSS in js, solid query, router and more)
The main issue here, I guess, is that solid-start (next js alternative) is in beta, yes.
Surely, there are no 10+ datepickers for solid, but you don't need much to build apps.
I definitely think NextJS opened the door for Solid because of just how much ecosystem gets thrown out with RSCs.
I hope solid gets proper funding, just like svelte
@@luka1790 Recently Solid team announced that they got a sponsorship from Google and now Google Aurora team will also work on solid start
Nice library, I felt like redux toolkit has more features than just being a state manager?
redux-toolkit has the query system, which this does not have.
They are literally taking the entire JavaFX observable and property library and slowly reimplementing it in react. I use Jotai currently but this is better.
I am done with react. Yes I am learning PHP and my sql and they save my time more than chatgpt + react
How long have you've been on React?
@@barayiti only half year
Legend... Wait for it... Dary.
Legendary!
womp womp. :)
Doesn't feel nice about this only reason bcoz of wrapping of the components . Have tried similiar kind of thing in redux and it makes difficult at times when we want to deal with the components which are wrapped . Just my POV . Do let us now your opinion about this issue.
Yeah, that `observer` thing is a little bit of a pain.
I abandoned HOC's five years ago. No thanks. Can't we all just agree on a state management solution by now? Besides 98% of apps need nothing more than react primatives and server state.
it looks kinda like vue
Oh, because of the proxy style. Yeah, that's just one way of doing it.
API wise ? How that ? In vue with ref and in script (just person.first works with reactive and in your template) you'd do person.value.first and not person.first.get(), and to set you'd just do person.value.first = '"bar" and not use set(), also you can't really mutate props in child component in vue like done here (well you can with the experimental defineModel and if you pass an object as prop and not a primitive value but it's per the docs a JS limitation that'd cost too much to prevent and it's not intended to be done that way) and have to use emit (or pass a setter like in react)
@@heroe1486 Yes, and if you want that exact thing you can use MobX or Valtio. IMHO, this API is closer to that Proxy style than something like a Zustand or Redux in that you don't have to have action functions to set values. You can just set a value using `.set` directly (even though, yes, with MobX or VueX you could forego even the set.)
use vue
"this is a higher-order function ..." aaaaand I'm out...
While the fine-grained reactivity is cool, I don't think it's advisable. If you're going to be using React then you should use React's rendering model and mechanism. Updating the DOM behind React's back in an invitation for problems. Want to use fine-grained reactivity with JSX? Then use SolidJS or Qwik.
zustand or legend?
For me? For work projects? Probably Zustand for the time being just because of the support and usage. Legend state is still very new.
@@jherr +1 on that. Zustand works out of the box and is so easy to get started with.