Smarter and Simpler React State

Поделиться
HTML-код
  • Опубликовано: 6 сен 2024

Комментарии • 149

  • @jherr
    @jherr  Год назад +5

    To try everything Brilliant has to offer-free-for a full 30 days, visit brilliant.org/JackHerrington/. The first 200 of you will get 20% off Brilliant’s annual premium subscription.

    • @maurizioliberato
      @maurizioliberato Год назад

      Just subscribed to Brilliant, thank you for the discount! Also thank you for your RUclips videos, they are helping me a lot in advancing my skills! 👍

  • @victorlongon
    @victorlongon Год назад +35

    I actually think that the pure react implementation was the most straight forward. Not hard to follow at all. The other tools can be cool and maybe have more features, but having to use ref to store the value for the store, and put the stuff coming from the third part libraries in the context just feels like unnecessary complexity tbh. I appreciate the time you put into comparing those, though. I would probably reach for something like Zustand if I needed global state or more complex state, but I havent felt a need to really use anything else lately than react built in stuff (i do use graphql so server state is managed by Apollo). I think the benefits from this kind of tools, as I mentioned is that if have really complex state, so that adding new deps and a new api is actually worth it, imho.

    • @nivoset
      @nivoset Год назад +5

      I would think useReducer may simplify it down as well.

    • @somedude6420
      @somedude6420 Год назад +1

      ​@@nivosetI've been using that a lot more lately, and it made my code cleaner, instead of using multiple useStates

  • @devcampo366
    @devcampo366 Год назад +4

    I had some custom hooks that were starting to grow quite large and complex ito dependencies, and now there’s a way I can simply apply some refactoring to use my current “global” SM (zustand) in “local” context. Thanks Jack, this was REALLY helpful.

  • @Svish_
    @Svish_ Год назад +9

    I feel like the initial example would've been a lot cleaner and simpler if you'd just used a single `useReducer` hook to mange the state of your context, rather than multiple `useState` 🤔

  • @Pyrospower
    @Pyrospower Год назад +5

    Great video! I'm a beginner and I haven't used state management libraries yet, so this video was very interesting to me

  • @ercnomic
    @ercnomic Год назад +6

    I love jotai, the ability to completely separate the whole business logic from the ui is really good, from my experience if you want to create component that has it's own atom better combine it with jotai molecule.

  • @israelssantanna
    @israelssantanna Год назад +7

    Thank you! This kind of content (comparison of tools) is extremely helpful 😊

    • @jherr
      @jherr  Год назад +1

      Glad it was helpful!

  • @user-mw6ny9xy4r
    @user-mw6ny9xy4r Год назад +3

    What a lifetime saver! A more welcome video because it's a topic I'm thinking about these days! thank you!

  • @MrinmoyRoy1990
    @MrinmoyRoy1990 Год назад +8

    Great video! I'm relatively new to React, but have worked with Vue for a couple of years. So Valtio felt a lot like Vue to me. I think its because the proxy get/set. Zustand confused me a little bit. So naturally I thought I would be using Valtio for my next project. But then again you made Jotai sound way cooler with all the extra features that you mentioned.

    • @jherr
      @jherr  Год назад +3

      Jotai is wicked cool.

  • @boot-strapper
    @boot-strapper Год назад +3

    it sounds like you made these library names up while high as a kite

    • @jherr
      @jherr  Год назад +1

      Blame Dai-shi Kato. Haha.

  • @nigeldasilvalima4568
    @nigeldasilvalima4568 Год назад +1

    Man. I think this is the first ad in a tutorial video that I really got interested to. Thanks for the great tutorial and also for the sponsor of the week

  • @erikslorenz
    @erikslorenz Год назад +2

    I've been all about jotai for the last few months. I hit that point of the year where I'm redoing the ui of some internal apps with some updates and jotai has really made things nice

    • @spongebob93lover
      @spongebob93lover Год назад

      hi, are you using jotai for managing ui state or server state or both? i'm currently in the middle of choosing which state manager to use in my e-commerce project :D

  • @slashieaward
    @slashieaward Год назад +3

    This is such a love letter to Dai-shi and I love that. One question: Redux strongly recommends a single store for the entire application, managed with slices. It's one of the things I dislike most about it. Zustand is also "one-way," but does it take a similar philosophical position?

    • @jherr
      @jherr  Год назад

      Not that I know of. I have a bunch of small Zustand stores in one app and it's fine.

  • @OnceABustAlwaysABust
    @OnceABustAlwaysABust Год назад +5

    I hope the React team comes up with better design for hooks in the future. In the meantime I’m ok to use the built in state management tools. The deps array sucks but it’s become second nature and I never need to think about it. Also ESLint is always there if I miss something

    • @Epic0n
      @Epic0n Год назад

      I permanently intersect with people who infinitely push an array of dependencies in memo and callback. And I ask them what do you think about all this. And do you know what is the most popular answer? If Facebook decided so it is the best solution. After this kind of answer, I want to suicide. Actually I joke )))

  • @VKD007
    @VKD007 Год назад +2

    Another amazing video. I watch these sort of videos and read articles too.
    Ill share this with others who are struggling with react and state.
    I guess most of the complex apps use inhouse stores with deep nested objects

  • @doit7582
    @doit7582 Год назад +3

    Personally, basic implementation is easy to follow, and Valtio looks nice

  • @Gasshette
    @Gasshette Год назад +1

    Thanks for the video, a gold mine as always ! I might have missed the information but this in purely about migrating state from React context to another solution right ? Because for example, storing the Zustand state in a ref isn't nessessary at all when you start an app with it. As you said, you are using "createStore" which creates a store that is disconnected from React, that's why you need to store the state in a ref and provide it with the existing React context.

  • @tuttsj
    @tuttsj Год назад +3

    Great video, thank you. I have a question 😅, you have a useEffect in your thumbnail which has the dependency array, but the only dependency array you demo with the idiomatic React APIs is useMemo. Curious if you had any examples with useEffect that are resolved by using the other state libraries, or whether it's predominately the derived state. Thanks again!

    • @jherr
      @jherr  Год назад +2

      True, I should have used useEffect as the example because the case is actually stronger for that. Zustand, Valtio and Jotai make async work a lot simpler, cleaner and easier to debug than using useEffects to do async work.

  • @sjcEBJr
    @sjcEBJr 7 месяцев назад

    Hy Jack. Very nice video. Thanks a lot. I just wondering if you need to create dynamically and access the state outside the context (for moderation, for example).
    In this case, the most straight forward solution would be have chat in array in a global statemanager. However, this means deal with complex nested state. Could I still use this pattern and have a global store to hold multiple instances of chatStore? What do you think?

  • @jgkdmdevienjjgg8866
    @jgkdmdevienjjgg8866 10 месяцев назад

    When i need complex state i use non reactive state (object inside of useRef) and manual rerender (setDummyState({}) when i know data has changed. But still have to use dependency arrays for effects

  • @Cahnisama
    @Cahnisama Год назад +1

    I love the thumbnail, great idea

  • @micelumail5829
    @micelumail5829 Год назад +1

    Thank Jack, we've been using Jotai too, it's really awesome
    In newest project, we use Xoid, feels good too; anyone has experience using it?

  • @jasonthorpe3470
    @jasonthorpe3470 Год назад

    Love it as always. FYI, At 6:05, the bit where you replace the value of the context with the store gets cut off, which is a little confusing for folks who aren't familiar with using react context

  •  Год назад +1

    0:52 crime scene of some animal in the back yard stealing food 😅

  • @thisguy5718
    @thisguy5718 Год назад +1

    this is a really good video , i have been using react the past 2 years and starting to get frustated with react state management lol
    so i think its time for me to get into Valtio and other stuff

  • @ouss
    @ouss Год назад +15

    I was distracted by the guy climbing a tree in the background in the intro

    • @trulymittal
      @trulymittal Год назад +1

      1:28 once I read ur comment, can’t take my eyes of him.

    • @DevRel1
      @DevRel1 Год назад

      I was distracted by shoooszhtaaaand. lol jk

  • @IainSimmons
    @IainSimmons Год назад

    Jotai reminds me of Solid's signals (I think Jotai has signals now too?) and Valtio reminds me of Solid's stores.
    Anyways, great video, though I don't think this highlights the strengths of the state management libraries, particularly when using for actual global state vs React's Context (you probably already have a video for that)

  • @ionelCristianLupu_
    @ionelCristianLupu_ Год назад +1

    would've been nice to see the difference in render between the first simple example and all other examples. Beginners might be tempted to choose the first option just because it's using built-in API and actually looks cleaner than Zustand for example

    • @jherr
      @jherr  Год назад +1

      With proper use (I.e. selectors in the case of zustand) all of these have the same number of re-renders.

    • @netalev2228
      @netalev2228 11 месяцев назад

      I would assume the first version (react context) will cause more rerenders than the others? Am I wrong? did I miss something? thanks!@@jherr

  • @harshilparmar9076
    @harshilparmar9076 Год назад

    Hey Jack, This is awesome as usual. I have one question though what are the pros and cons of making individual hooks as you have done in video and not just export everything from one hook?

  • @mappy7954
    @mappy7954 Год назад +1

    This was a great comparison. One question, for the jotai example could we get rid of the react context and jotai store by wrapping each Chat in a jotai ?

    • @jherr
      @jherr  Год назад +1

      Not sure about that. You should give it a go and let us know!

    • @mappy7954
      @mappy7954 Год назад +1

      @@jherr ​ @Jack Herrington I forked the repo and made the change. I'm glad I tried b/c it seems to work! It cleans up the hooks a lot and there are no more imports from react.

    • @mappy7954
      @mappy7954 Год назад +1

      I would post the github link but I think RUclips's filter is blocking it. It's the fork from Brandoko.

    • @jherr
      @jherr  Год назад +1

      @@mappy7954 I'll check it out!

  • @breitseite-media
    @breitseite-media 27 дней назад

    Great Examples, i just encounter a problem if i want to initialize a value from router params for example.
    I then take useEffect and set a value in the context, but there is no rendering of the value change anymore.
    Could it be that the jotai provider is needed?
    const setCampaignIdFilter = useSetCampaignIdFilter();
    useEffect(() => {
    if (campaignId) {
    console.log('campaign id set -------------->')
    setCampaignIdFilter([campaignId]);
    }
    }, [
    campaignId,
    ])
    after that useCampaignIdFilter is still empty in the children.

    • @breitseite-media
      @breitseite-media 27 дней назад

      never mind it was just the the atom key, the implementer made a typo. Thanks ;)

  • @cdcasey
    @cdcasey Год назад +1

    With the latest React docs recommending using a framework (Next, Remix, Gatsby, etc) instead of just building a SPA, do you think global state management libraries still have a place when building a React app with a framework?

    • @jherr
      @jherr  Год назад

      AFAIK they do cover SPA and offer Vite as an option in that space. It's not clear to me the connection you are making between a "framework" and a global state manager. Those two things are orthogonal to me. An application that uses SSR/SSG can also use global state managers to manage complex state on the client, I do that every day.

    • @cdcasey
      @cdcasey Год назад

      @@jherr I agree that they are generally orthogonal concerns. But I've always assumed (and seen a couple of headlines confirming my bias) that using a state manager like Redux (or one of the ones you demoed) with a framework like NextJS was a bit of an anti-pattern. I have not looked at the matter too deeply, though, and I find it interesting that you do use this pattern. I will keep that in mind and investigate further. I'd love to hear any other thoughts/insights you have on the matter.

    • @jherr
      @jherr  Год назад +1

      @@cdcasey Truth be told I don't use Redux on NextJS or anywhere else. This is more of a viewer request video. But I do use state managers on NextJS and it's usually a combination of React-Query and Zustand for managing more complex client side state.
      I think the reason that it would be considered an anti-pattern is that getServerSideProps already does so much for the page that a state manager to do the queries is kind of ... pointless. That being said, if your site is a combination of mostly static pages (e.g. product details) and forms pages (e.g. checkout) then a state manager for the forms pages that you may pre-load with some data from getServerSideProps makes sense. Although there are lots of options in the state manager/forms manager/query manager space and you might not need a state manager.

  • @viniciusdacruzsoranco4470
    @viniciusdacruzsoranco4470 Год назад +1

    Maybe dumb question (Zustand): how the changes are being shown on the screen if the store was stored to a useRef?

    • @jherr
      @jherr  Год назад

      The store is held in a useRef, and passed around but it's calling the useStore hooks with those stores that connect it to the React framework.

  • @kemcadams7210
    @kemcadams7210 Год назад +1

    What is derived data. I have an app where i need to examine the user login properties to determine what the user can have access to - is this the same as derived data?
    there is a squirrel in the background of this video attacking the bird feeder. 🙂

    • @jherr
      @jherr  Год назад +1

      Yeah, that would be derived data. Basically anything that is some kind of synchronous operation to create some new data from one or more pieces of existing data. Like the grand total of a bill would be derived data from the items in the bill, the tax rate, etc. The idea is not to have to manually update the derived data. To instead let the state manager compute the grand total (in this case) any time the referenced data changes.
      And yes, the squirrels definitely get acrobatic back there. We've ended up having to coat the birdseed in capsicum powder. The birds don't notice but the squirrels hate it. I've got nothing against squirrels though, they just have their own feeder on the other side of the yard.

  • @brownjedi
    @brownjedi Год назад +1

    This is amazing! Thank you!

  • @jeromemarshall9248
    @jeromemarshall9248 Год назад

    Awesome video!
    BTW, how do you get all the suggestions in your terminal?

  • @avkonst
    @avkonst Год назад

    Hookstate does global and local states same way and same API. It does not require to create any functions or variables outside of a component to achieve better local state. Moving a state from local to global is literally moving a variable from a component function to a shared variable, no component changes are required.

    • @jherr
      @jherr  Год назад

      Except that it's not actually global. These solutions, effectively, store their data in a ref associated with the component.

  • @MuhammadFahreza
    @MuhammadFahreza Год назад

    Hi Jack, great video as always. I would like to ask, do you agree that across these 4 implementations, Zustand is the easiest for making unit test? or what implementation you opt for complex business logic ..

    • @jherr
      @jherr  Год назад

      For work, probably Zustand, for myself probably Jotai. I think Jotai is the most interesting and powerful, but Zustand is the more conventional chocie.

  • @Tarabass
    @Tarabass Год назад

    But how about rerendering of the components? Is the state manager not subscribed to all components and therefore rerender all of them?
    More and more I'm thinking that I will stick to Vue lol. But that's also because I'm now mapping all features in my head from Vue to React and things like dependency arrays are very frustrating..

  • @thiagomoraes791
    @thiagomoraes791 Год назад +2

    really great content

  • @user-jr8th2rm8j
    @user-jr8th2rm8j Год назад

    hi jack , could you please make the video
    How to create micro frontend application using nextjs in npm from bigining .

  • @martinvirando5651
    @martinvirando5651 Год назад +1

    I'm looking at this wondering "Is this really easier than using vanilla js"?

  • @fooked1
    @fooked1 Год назад

    Why use the store and context/provider in jotai? Doesn't that cause a re-render of the tree that's in that provider?

  • @anshnanda
    @anshnanda Год назад +1

    Can you do something like this for MobX and MST?

  • @thehangover4985
    @thehangover4985 Год назад +2

    Another Great Video.
    * infinite clap *

  • @sohanreddy600
    @sohanreddy600 Год назад

    You like saying the word Zustand very much 😄

  • @gosnooky
    @gosnooky Год назад +1

    Love your content, but at times your editing is a bit fast, and you cut away like at 18:14 and can't see what you type or paste

  • @uhl7792
    @uhl7792 Год назад

    Where do you get ideas for videos? Always so good!

    • @jherr
      @jherr  Год назад

      In this case Jotai released a new API with this store model and I was like, hey, can other state managers do that too, and ... video.

  • @ayushjain7023
    @ayushjain7023 Год назад +2

    Hey Jack one question how single context with non intersecting values provided to the multiple providers created by this same context (as you described in the video ) is different from using different contexts with different providers ? Can you please explain the differences in deep 🙏

    • @jherr
      @jherr  Год назад +1

      I'd love to help you, but I really don't understand your question. How is the same context schema, reused in multiple instances different from different context schemas used with different context providers?

    • @kristopherhaney
      @kristopherhaney Год назад +1

      ​@@jherrI think he's saying "why not have one root context provider with, say, an array of chats, instead of a separate context provider for each chat"
      But I could be misinterpreting

    • @jherr
      @jherr  Год назад +2

      @@kristopherhaney If that's the case then great question. What I was trying to demonstrate was that you could have isolated local state but manage it with what we would normally call a "global" state manager. I admit that this was a kind of an arbitrary example, and you could totally do this with a shared store.
      That's one of the issues of RUclips is I want to convey a pattern through an example, but not have the example itself be so large as to overwhelm the pattern. Which leads to the inevitable; you could do this simple project so much simpler with X, Y, and Z, which is often times true. So I just rely on folks to look through my example to see if the pattern is interesting to them in their own applications.

    • @ayushjain7023
      @ayushjain7023 Год назад

      @@jherr what I mean is that in your example you have used one create context and with the same context you have created four providers in the chat containers, how it is different from using 4 different context, what’s the main difference

    • @ayushjain7023
      @ayushjain7023 Год назад

      @@jherr and also how and why keeping same context helping in this case , is it that when we create multiple providers with the same context, it make the states isolated? If so then how ?

  • @r.osorio02
    @r.osorio02 5 месяцев назад

    What is the true benefit of all these alternatives to hooks? If you tell me readability, sorry, I’m not convinced. Performance means more for me than something so useless as readability

  • @gpenner
    @gpenner Год назад +1

    Is there any performance issue for having tons of global states on the app? Do we need to clean up after we’re done?
    I’ve been using Jotai and it makes it super easy and simple to test a few component since I can hydrate the state very easily

    • @jherr
      @jherr  Год назад +1

      These managers are just as efficient at storing state as React. React state is effectively outside the component just like this.

  • @Chrosam
    @Chrosam Год назад +1

    Amazing as always 🔥

  • @venicebeachsurfer
    @venicebeachsurfer Год назад

    You can use Zustand for local state WITHOUT the context right - is there any benefit to wrapping it in a context Provider - I see the need if your components are the same, and they need to maintain their "own" state - but lets just say you had one chat box. You can still create a small zustand store without the context, right?

    • @jherr
      @jherr  Год назад

      Yeah, you can use all of these without a context provider.

  • @victorseara9970
    @victorseara9970 Год назад

    Is the context provider really a must when using this libraries? If I'm not mistaken, we can have access to the values without it. I think using context provider can make it easier to swap one strategy with another abstracting how you access the values but in these examples it looks irrelevant. Am I confusing things a bit?

    • @jherr
      @jherr  Год назад +1

      The context at in this example is showing allowing for local state for each of the different chat windows. Is it strictly necessary? No. We could have a global store and pass in a GUID for each chat in this case. But what I'm trying to show is using the context to create a local scope for a "global" state manager.

    • @victorseara9970
      @victorseara9970 Год назад

      @@jherr thank you. It's clear now and it's also a pretty good solution for that use cases. I'll watch it again to get a better understanding. Thank you for you clarification!

  • @RahCodes
    @RahCodes Год назад

    The only problem with dependency arrays is that people think that, because they exist, you're supposed to make decisions there about when things happen. This is the wrong mental model. Just follow the lint rule and, if you somehow think you need to do something weird in the array, reconsider your approach.

    • @jherr
      @jherr  Год назад

      I don't know, I think that's kinda limiting. I've definitely put expressions into dependency arrays [isLoaded && !isError] or whatever (just made that example up so ... don't look too much into that :) ).

  • @CistiC0987
    @CistiC0987 Год назад

    I like so much the autocomplete feature in your terminal? With that sweet drop down with command options. Is that some kind of (zsh or something) plugin?

    • @claus4tw
      @claus4tw Год назад +2

      It’s either warp as a terminal or it’s fig for the normal terminal

    • @victorlongon
      @victorlongon Год назад +1

      It is fig, he is using vs code built in terminal

    • @jherr
      @jherr  Год назад +1

      Spot on Victor.

    • @victorlongon
      @victorlongon Год назад

      @@jherr I have started using warp now, it is super super nice

    • @jherr
      @jherr  Год назад +1

      @@victorlongon Cool! I'm still on iTerm for my work machine, and I'm using either Tabby or Warp (or the integrated terminal in VSCode) on my personal machine.

  • @docmars
    @docmars Год назад

    Is there a way to isolate stores for each chat container without using React Context? Do these stores provide ways to instance themselves, where you could theoretically only use their hooks to interact with the store, without polluting a single instance?
    Half the reason I want to use a 3rd party store library is to avoid Typescript hell with React Contexts. It's unbearably fiddly to get it right.

    • @alexisnavarro3766
      @alexisnavarro3766 Год назад

      .

    • @jherr
      @jherr  Год назад +1

      You could store all the chats in a global store and manage it by ID, but there is a potential there that one chat could accidentally get content from another chat.

  • @frankbardon
    @frankbardon Год назад

    Could have just used useReducer with its dispatch function.

    • @jherr
      @jherr  Год назад

      Yes, that is another option for the hooks based version.

  • @aan1874
    @aan1874 Год назад

    Hi Jack! I wanna learn JS and React, but with Web Assembly and Blazor, what is the future of React? Thank you!

    • @jherr
      @jherr  Год назад

      You want to learn JS and React but use WebAssembly and Blazor to do that? That doesn't make any sense to me.

    • @aan1874
      @aan1874 Год назад

      @@jherr I have heard that Blazor will get as big as React and Angular In a couple of years and that it will be more convenient to use it than React so people will start using that more

  • @kevinbatdorf
    @kevinbatdorf Год назад

    just use eslint with the react hooks rules enabled

  • @WendtRiding
    @WendtRiding Год назад

    If you could only pick one of the suggestions, which one would you choose?

  • @MsPrakhar12
    @MsPrakhar12 Год назад +1

    loved it ♥︎

  • @Goshified
    @Goshified Год назад

    While dependency arrays in React are annoying, I think the hate from them mostly comes from devs not quite understanding how references work in JS (and also not using a linter which fills them out automatically).

  • @viper_eyes
    @viper_eyes Год назад +2

    Bro , grow your beard again , you look waaaaaaaaaaaaaaaaaaaaaaaaaaaaaay better with it

  • @brayandvelasquez2256
    @brayandvelasquez2256 Год назад +1

    But if we really need to call a function 1 time using useEffect???

    • @jherr
      @jherr  Год назад +1

      You can handle that as you create the context, it will only be created once.

  • @asgernorskovbak1811
    @asgernorskovbak1811 Год назад +1

    xstate maybe?

  • @p1erceprc
    @p1erceprc Год назад

    what theme is this?

    • @jherr
      @jherr  Год назад +1

      Night Wolf [black]

  • @inasuma8180
    @inasuma8180 Год назад +2

    It does feel like a tradeoff. You're skipping React-bound utilities for 3rd parties that may or may not be supported long term. Valtio, while really cool, is a pretty small project. I don't like dependency arrays but tools from the React team have stability.

  • @jayg5123
    @jayg5123 Год назад

    theme?

    • @jherr
      @jherr  Год назад

      Probably Night Wolf [black]

  • @inversemetric
    @inversemetric Год назад

    I'm surprised you need contexts at all to do this

  • @greendsnow
    @greendsnow Год назад +1

    Valtio is the easiest.

  • @4DChess
    @4DChess Год назад +8

    Found it hard to follow honestly, because of everything being predeclared was not able to keep up the context

  • @taukirsheikh9405
    @taukirsheikh9405 Год назад

    is your background real or CSS

  • @luxnox9303
    @luxnox9303 Год назад

    The absolute horror of using context for state management.

  • @drodsou
    @drodsou Год назад +2

    I'm so glad I moved away from React. I loved it, but it ended for me when hooks started hyping. At first I thought I just did not get them, but as years pass I reafirm myself that this looks like a kind of an ideological sect that has taken over web development. Of course I am a nobody and probably wrong.

  • @NurfHerderEclipse
    @NurfHerderEclipse Год назад +3

    React is an anti-pattern.
    Hooks encourage async coupling.

  • @TabuHana
    @TabuHana Год назад

    Man I swear i cant follow any of your vids

    • @jherr
      @jherr  Год назад

      Sorry about that.

  • @user-yi7ec6rv9p
    @user-yi7ec6rv9p Год назад

    13:25 why not just `useChatStore.setState({ currentMessage: 'new message' })` directly from the consumer ?
    Do we really need `setCurrentMessage` and `addMessage` ?