You still use Redux?

Поділитися
Вставка
  • Опубліковано 8 лип 2024
  • Become a member for rare memes:
    / @t3dotgg Also watch live on twitch / theo
    React State management is in a crazy place. So many options!!! How do you pick the right one?? Let's chat about it!
    Keywords REACTJS REDUX JOTAI ZUSTAND RTK RTK-QUERY REACTQUERY REACT QUERY MOBX XSTATE SWR STATE MACHINES
    Timestamps:
    00:00 intro
    03:29 what is state?
    06:34 coding example
    20:23 what isn't server state
    25:05 why didn't useState work?
    25:33 jotai
    28:25 zustand
    33:09 xstate
    35:34 conclusion and outro
    Local Elevator by Kevin MacLeod is licensed under a Creative Commons Attribution 4.0 licence. creativecommons.org/licenses/...
    Source: incompetech.com/music/royalty-...
    Artist: incompetech.com/
  • Наука та технологія

КОМЕНТАРІ • 311

  • @davidkhourshid4450
    @davidkhourshid4450 Рік тому +191

    Note: the default fetch example in the XState visualizer is just a contrived example of modeling a promise; it's definitely not meant to be the way you fetch data.
    In fact, fetching data is just a single "invoke" in a state, with optional onDone and onError handlers. That's it!
    Maybe I should change the default example 🤔

    • @Rmp613
      @Rmp613 Рік тому +13

      Yeah I think its worth changing the default example

    • @branthology
      @branthology Рік тому

      Definitely

    • @kassios
      @kassios Рік тому +11

      @David Khourshid I think they are missing the point of xState as a tool to model the UI behaviour.
      This is a very useful layer of describing the User Interaction Flow. What the user can and cannot do at any giving point. Which elements are interactive or disabled/hidden based on where in the flow diagram the user currently is (the specific finite state).
      I think the ambiguity springs from the double meaning of the word state.
      State in React and (finite) State in xState are different things!
      We are used to store or derive UX conditions (loading, canSubmit, isDisabled) in the React State, while xState explicitly models those conditions as finite states.
      Anytime you have transitions in your app which affect the interactivity of visual elements xState offers a great solution.
      As a bonus you get a diagram for your documentation 🙂

    • @raulcontreras2717
      @raulcontreras2717 Рік тому +7

      I love xstate, but the features react-query offers regarding data fetching are not easily implemented in xstate, I really believe xstate needs an xstate-query package which implements this features using a state machine easy to use. Not as trivial as you point out -> "fetching data is just a single "invoke" in a state, with optional onDone and onError handlers. That's it!"... No

  • @jake1087
    @jake1087 Рік тому +209

    so jotai is a global useState and zustand is a global useReducer

    • @lucabaxter4002
      @lucabaxter4002 Рік тому +11

      yes, with the difference that jotai has to be used in the React Tree, while zustand does not. Both the best btw.

    • @dhidhi1000
      @dhidhi1000 Рік тому +1

      zustand is also global?

    • @lord_kh4n
      @lord_kh4n Рік тому +3

      @@dhidhi1000 yes, it is flux

    • @bardhokajvazi2726
      @bardhokajvazi2726 Рік тому +1

      I will screenshot this

    • @offlercrocgod
      @offlercrocgod 10 місяців тому +1

      Zustand stores don't have to be global. You can create multiple instances of the same store and pass them down using context.

  • @youssefaserrar2001
    @youssefaserrar2001 Рік тому +74

    Explaining to the world that server state and client state are 2 different things and they should be separated was the best thing team react-query did, and when we think about it most of our state is server state that can be handled perfectly by react-query.
    Great video 👍

    • @troy5370
      @troy5370 Рік тому +3

      Why do you and the author make this assumption, "most of our state is server state" ? That is about as bad as the code in the video combining data access directly in the components. Isn't this "REACT" not "Let's Go A Polling"? The only time that most of the state is server state is when you doing an app that has almost no interaction ie. mostly read only displays with a filter at most. If you have an app with actual user interaction, no that isn't the case at all. Now you say web apps need 2 state managers rofl. If your so concerned about state why not use something like SignalR that pushes "real" changes from the server instead of wasting time polling for changes that may or may not exist...why guess with this crud when you could know? GUI Blooper: never assume what the user wants to do and try to do it for them. Newsflash, the client will never be in sync nor should you ever assume it is unless that is its specific function ie Stock ticker. Try React Query with a bad network connection as it destroys itself trying to sync and your app sits in loading limbo

    • @user-fr2fm3ri3w
      @user-fr2fm3ri3w Рік тому +5

      @@troy5370bro thinks we reading that 🥶

  • @keemcodes
    @keemcodes Рік тому +62

    Loving your content bro. You're definitely my go to for keeping up with frontend tech.

  • @TannerBarcelos
    @TannerBarcelos Рік тому +109

    React Query + Zustand + useState are the go tos for all my state needs (local, server data, global). All of this makes your app light weight too - it’s less of a headache to maintain and each api , respectively is self explanatory, well documented in the library docs, and keeps things feeling “reacty” all the time. I have used redux a lot and use it on a project at work, but given I’m leading the UI efforts on this app, I am considering a complete overhaul to using React Query and Zustand - feel like the project would increase in network performance, rendering performance out of the box, etc.

    • @OzzyTheGiant
      @OzzyTheGiant Рік тому +3

      As someone who hates using React at all, this seems like the best stack to use if I'm forced to write React code.

    • @TannerBarcelos
      @TannerBarcelos Рік тому +2

      @@OzzyTheGiant while I do like redux / use it at work, this stack is both modern but also way more light weight. Makes the react code a little less bloated. I will agree though, React is a headache more often than not. I enjoy it and it’s probably my top skill in the frontend side of things however I can agree with your take on you hating writing it. It becomes too much of a hassle

    • @youusef101
      @youusef101 Рік тому +8

      @@zz-if1ic In my point of Vue he must be a view user 😄

    • @SuhweeSoftware
      @SuhweeSoftware Рік тому

      did you end up rewriting it to Zustand and React Query? If so how did that go?

    • @adimardev1550
      @adimardev1550 Рік тому

      i really don't understand why people love redux or RTK while i hate it so much for very practical reason.

  • @jherr
    @jherr Рік тому +51

    Fantastic video!

    • @dalebradleygordon
      @dalebradleygordon Рік тому +4

      Top 10 best developer crossovers 👨🏻‍💻👨🏼‍💻
      PS: Thanks for work you both do! Always come away from the video you guys release amped to build something truely considered and extraordinary 🎉

    • @thiscris_
      @thiscris_ Рік тому

      Love you Jack, you are the nicest guy.

  • @StephenRayner
    @StephenRayner Рік тому +20

    Showing failure is always good

  • @theindieprogrammer
    @theindieprogrammer Рік тому +30

    About the counter example with Jotai, actually it's very simple to implement, you just create another atom that increments the counter atom. Here:
    const counterAtom = atom(0);
    const incrementAtom = atom(null, (get, set) => {
    set(counterAtom, get(counterAtom) + 1);
    });
    // On your component
    const counter = useAtomValue(counterAtom);
    const increment = useSetAtom(incrementAtom);
    increment();

  • @0xTomster
    @0xTomster Рік тому +1

    Awesome freaking video. Thanks Theo you explain things in a way that is so easy to understand!

  • @sim.b
    @sim.b Рік тому +2

    Really interesting video !
    You explained what the two different types of state needed in front-end apps: Application State / Server State.
    RQ will help a lot to sync with the server state, but to me its not helping that much if you want to create a proper data-layer.
    Complex front-end apps may require data-layer that have the responsability to abstract the presentation logic (view model) as well as the business logic. Also this layer should be easily testable, so its better if its no tightly coupled with the UI (like RQ).
    I am wondering how RQ can scale on larger/complex codebases ?
    That being said, RQ would be my go tos if I have top-notch API, or if I use a BFF that generate my read model.

  • @Euquila
    @Euquila Рік тому +2

    Context _can_ be _extremely_ useful in the following situation: i'm using a 3rd party component library that has a renderCell prop in an array-schema which gets passed as a prop to the component. I have no bloody idea how to pass props to the component I attach to renderCell. Here context is an absolute hero!
    Edit: I will also add that I enjoy Zustand's API so much to help me write cleaner code. When my components get bloated and I'm due for a refactor, I'll often reach for Zustand instead of moving the code to a custom hook. I just find it easier

  • @emab
    @emab Рік тому +1

    Really interesting video. The project I’m working on is moving to GQL so I’m going to try push this more for some of our applications.

  • @theory-in-motion
    @theory-in-motion Рік тому +7

    The reason for using XState is to enforce invariants in cases which _must_ not happen. It's for formally proving, for instance, that it's impossible to have a hot-mic moment where you switch rooms or scenes (or whatever), and the camera followed you, but the mic didn't, or the mic is broadcast in two different places.
    It's essentially for enforcing the same kind of rigor that should be enforced when making good hardware. Aunt Gertrude's cat blog doesn't need that rigor; medical devices often should (but most likely don't).

  • @creatorsremose
    @creatorsremose Рік тому

    This was so helpful for what I'm working on that I subscribed while entranced. Thanks!

  • @ShaharHarshuv
    @ShaharHarshuv Рік тому

    One of the more interesting talks I've seen on this channel. I'll definetly check these libraries out

  • @lucabaxter4002
    @lucabaxter4002 Рік тому +2

    I was surprised when you mentioned 2 of my favourites state managament libs! Jotai is amazing, it is so scalable! One thing tho Theo, what if i have to sync data from the server with serverSideProps to the client state in Jotai ? i tried it a while back and is a bit confusing the way you have to use useHydrateAtoms from Jotai. Do you have any suggestions or would you mind to explain it in a following video?

  • @vikingthedude
    @vikingthedude Рік тому

    Great breakdown of the different state management tools. What do you think of SWR by vercel? It's meant to solve the same state-sync challenges like react-query. But idk if it's as good or better than react-query

  • @webdevalextv8342
    @webdevalextv8342 Рік тому +9

    We are using Zustand more than a year in production. I like it a lot. Also for private projects.

    • @ts8960
      @ts8960 Рік тому

      why not useReducer

    • @abdelhameedhamdy
      @abdelhameedhamdy Рік тому

      Me too

    • @Euquila
      @Euquila Рік тому

      @@ts8960 useReducer is essentially just useState. Zustand is a "machine" that lives outside the components' lifecycles. It can also run async code which useState/useReducer cannot

  • @Slashx92
    @Slashx92 Рік тому +6

    We're using react context for complex forms that have user actions that could change the layout and features of the form, and I find it great. Using it in pair with state for individual inputs and containers seems like a no-brainier for our use case. We use react as the UI of embedded forms for a CRM.
    Since the context here resembles something like the "settings" of the form, and they are essentially an SPA with a single form, I think it's the perfect use case for it.
    With that said, zustand looks like all the good things about context without the bad ones (re-renders) I will definitively look it up
    I touched redux toolkit for a job interview and man that thing is like boilerplate galore if you want to just manage the state of a page

    • @Andreas-gh6is
      @Andreas-gh6is Рік тому +8

      Using the context API for state management means using mutable data structures. This can lead to some subtle and some not so subtle bugs. It's harder to reason about what the reconciliation algorithm will do. For many usecases, this works quite well, and it suits developers who prefer to think in an "iterative" rather than "functional" / "reactive" way. But React isn't named React for nothing. "useState" and "useReducer" are superior to the context api. The purpose of the context API is to hand down data along a component tree and to avoid coupling components to a particular source. Also I found that Redux makes state handling extremely transparen, easier to debug, trivial to test. This doesn't matter in the simplest usecases, but for me it almost always does matter. I find that people underestimate state management in general and that all the "boilerplating" of redux mostly means thinking clearly about state, computed state and state transitions.

    • @nivaldolemos5280
      @nivaldolemos5280 Рік тому

      Consider using react-hook-form. It even has a FormProvider for what you appear to be doing, but it makes massive use of refs internally to prevent unneeded rerenders.

    • @benkatz8999
      @benkatz8999 15 днів тому

      I have a similar application and just switched to zustand from context. never going back

  • @andrews8733
    @andrews8733 Рік тому

    This was super helpful, ty. I've been introducing context lately as a means of getting away from redux. Feels clunky sometimes. Might try some of these out instead.

    • @BobbyBundlez
      @BobbyBundlez Рік тому

      I guess im too new in this. but how tf does context feel more clunky than redux..

    • @dave_jones
      @dave_jones Рік тому

      @@BobbyBundlez maybe OP means that context was clunky when building class based components... but hooks make it pretty trivial. Still, it shouldn't be used willy nilly

  • @emday4prez
    @emday4prez Рік тому +5

    I can’t thank you enough for all of your videos.

  • @xan3xx443
    @xan3xx443 Рік тому +1

    Just started well a year ago I started react blindly almost never reading docs and just learning as I go. You don’t know how much reliefs your videos bring me because I’ve done almost everything the same as you. Also fuck all those tutorials where people don’t really know what they are doing like using craco. Even when I just started using react like a month into it I just saw it was a pile of hot shit and just never touched it. I like stoking my ego but mostly I just feel lucky

    • @Andreas-gh6is
      @Andreas-gh6is Рік тому

      The danger with stumbling through React this way is that people often don't get why React and Redux where created. To actually understand their nature and benefits, and to use React fully, one needs to grasp the idea of functional programming. Maybe not in the purest and most theoretical way, but React wants you to think in a functional programming mindset. React hates side effects and avoiding the "boilerplate" of redux usually leads to not being clear about side effect handling.

  • @KazimKassam
    @KazimKassam Рік тому

    I'm fairly new to React and I loved this video for explaining the different types of state. I did have one question - you said that UseMutation can alter the data on the server, is this with any server running any database? Could I alter a value on a Firestore DB using UseMutation for example? Or does it only work with certain backends?

  • @shinodinhaa
    @shinodinhaa Рік тому

    WIth Jotai, you can create a custom hook to expose some custom functions for it based on the actual value of the atom, instead of just using the useAtom directly in your code.

  • @bhushanpatil1760
    @bhushanpatil1760 Рік тому

    In jotai to just increment the state you can use derived atoms which can just update the state just by calling the increment function without any paramter.

  • @nickchauhan
    @nickchauhan Рік тому +21

    Redux RTK query is also very great tool for server state. It provides automatic hooks, caching, invalid cache on Mutation, provide tags to your data.
    If you have huge rest API it’s definitely a good tool to use. It has his own structure to follow but it’s worth it.
    I’ve experience in all three state lib react-query, zustand and RTK. I feel RTK query is good in terms where you have many endpoints to manage.

    • @DarkzarichV2
      @DarkzarichV2 Рік тому +1

      redux and rtk in general are very boilerplaty, that's why people tend to choose nowadays something... less of that like mobx, zustand etc

    • @phryneas
      @phryneas Рік тому +11

      @@DarkzarichV2 If you have it set up RTK Query once, you add a new endpoint with 1-3 lines of code and get a hook to use in your component that does data fetching, caching, automatic cache collection, fetching states etc for you.
      How is that boilerplatey?

    • @DarkzarichV2
      @DarkzarichV2 Рік тому

      @@phryneas well, if we talk about more complex state, with modules each module will require extracting actions out of reducers, creating slices, then combining them eventually and some other stuff, might seem just a little but it's preferable not having to deal with it at all. I personally use Vue much more than React nowadays, and Pinia is state manager I use there, would be cool if React had something like Pinia, very neat tool

    • @ofamigeradoudd
      @ofamigeradoudd Рік тому +2

      RTK query is just awesome

    • @dmitrymatatov7639
      @dmitrymatatov7639 Рік тому +4

      @@ofamigeradoudd RTK Query is a piece of shit, when we are talking about integration with React Native, complex data fetching, persisting responses, and other tools (such as InfiniteScroll) it sucks. In other cases it's a good solution, but due to limitations that also limit your architecture, I strongly advice you not to use RTK-Query.

  • @OmarElmasry1
    @OmarElmasry1 Рік тому +4

    i was really hoping that you include RTK quary in this video

  • @andresvalenzuela
    @andresvalenzuela Рік тому

    Thank you for sharing your knowledge, I'm learning a lot with your videos. You give valuable and well explained information.

  • @CadisDiEtrama000
    @CadisDiEtrama000 Рік тому +1

    I heard you mention this in a couple of videos, but what do you mean when you say "write code outside React"? Do you mean outside the project but it's still connected to the project, or inside the project but outside components, or something else...? @31:02

    • @EdwinMartin
      @EdwinMartin 8 місяців тому

      Code outside react is all code on the page that’s not dependent of react. It’s run outside the render tree (and outside the router). If you remove react from the page, the code still runs.

  • @garfieldnate
    @garfieldnate 3 місяці тому

    I love that you leave in the debugging sections to show that development has these sorts of hiccups even when you're advanced XD Very helpful video. Thank you for sharing!

  • @Zullv
    @Zullv Рік тому +5

    react-query is the same size as reduxjs/toolkit in terms of bundle.
    and if you end up using react-query, jotai and zustand you'll be over the bundle size of the redux while also steadily reaching the same level of complexity. redux has a bit of complexity, but reduxjs/toolkit has gotten rid of a lot of that stuffy boilerplate.
    if you can only use jotai and zustand for your application then that's fine. But if you end up using 3 libraries to replace one, well, maybe you're just innovating for innovation's sake.

    • @red17electro
      @red17electro Рік тому +1

      Why would you use both Zustand & Jotai?

  • @mariumbegum7325
    @mariumbegum7325 Рік тому

    Very informative video! Brilliant work

  • @PhilipAlexanderHassialis
    @PhilipAlexanderHassialis Рік тому +35

    Excellent breakdown as usual! Zustand is easy, straightforward and I really like their approach towards creating stores.
    Nonetheless, it really depends on the context of the application you are building. For example, in the cases of the applicatios I usually deal with, we are talking bighuge forms with lots of fields, usually broken down in wizard-ey situations and respective bighuge states that demand really tricky breakdowns in parts that will be displayed AND interacted with etc. So all in all, Jotai is out of the question and Zustand gets to be almost as boilerplate-y as RTK. So, of course our company's go-to solution is RTK because it will perform adequately well and is a battle-tested technology for such kind of situations.
    I would love if one day you did the same kind of breakdown but in the context of e.g. an ERP / HRMS / CRM or other applications that need > 50-60 pieces of information per Entity (with dozens of Entities, that, yes, need to be kept on the application state because all of them may change from many parts of the application) and propose something.
    Great great great video as usual though.

  • @EpicManTv
    @EpicManTv Рік тому +1

    any thoughts about effector?

  • @almasayap9744
    @almasayap9744 Рік тому

    This saved me a lot of time! Thank you!

  • @franmastromarino
    @franmastromarino Рік тому

    Damn! now I want to refactor all my projects with redux. Thanks for this video Theo

  • @wiiktor1393
    @wiiktor1393 Рік тому

    Awesome video! You have presented it very well!!!

  • @MauroTrigo
    @MauroTrigo Рік тому

    Hey Theo, this video is amazing, really helpful!
    I think the title can be misleading, since it sounds more like a rant than an excellent overview of how to understand and apply _state management_.

    • @t3dotgg
      @t3dotgg  Рік тому +3

      I had a different title and nobody watched the video lmao

  • @voyager_ll
    @voyager_ll 5 місяців тому

    Thank you, this helps a lot with learning React as an experienced Angular dev. Most tutorials are for beginners and don’t cover this kind of stuff.

  • @joshuadraper8240
    @joshuadraper8240 Рік тому

    Good point, relying on the algorithm to show me your next video without subbing was quite silly. Thanks for the call out.

  • @kalahari8295
    @kalahari8295 Рік тому

    Learnt tons of concepts ❤️

  • @yb3985
    @yb3985 Рік тому

    Hey Theo. I wonder, what's font you are using???

  • @user-bx5zi1mv5t
    @user-bx5zi1mv5t Рік тому +4

    Any comment on when it might be necessary to reach for something like urql or apollo client where you get the benefit of a normalized state and ability of updating the cache without invalidating queries? I know react-query talks about normalization not being necessary but have you ran into situations or know of any common situations where normalization is useful?

    • @t3dotgg
      @t3dotgg  Рік тому +6

      Normalization is as useful as your GraphQL schema is good. Front end developers are not the ones who get to choose how good the schema is (100% dependent on backend).
      React Query was built to give the DX of Apollo without the cost of GraphQL. It has almost entirely eradicated the usecase for gql clients for me. The normalization and cache management in Apollo is also slow as hell and takes a TON of CPU cycles to make basic changes.
      If you have a very specific architecture problem solved by GraphQL as well as a specific UX problem solved by normalization, it's...fine? But generally best to avoid the huge costs to get there.

    • @user-bx5zi1mv5t
      @user-bx5zi1mv5t Рік тому +2

      @@t3dotgg Understandable. Great explanation and great video. Thanks for the response!

  • @khalednasr7952
    @khalednasr7952 Рік тому +1

    that was fucking amazing man. thank you!

  • @Ebiko
    @Ebiko Рік тому

    So,
    I think all those usecases are often limited to server - client GUI communication things.
    I'm currently trying to develop a cool functional Sudoku app, to learn this stuff.
    And within this lies the issue. (I also have a similar app, which needs a similar kind of state management, since I haven't thought of something better yet)
    For the sudoku game itself, I currently use a big useReducer inside a Context, it works, but I also realize that it's massive calculation stuff I don't need, since the game (sudoku board, and sub components involved) constantly are recalculated.
    In case of the sudoku it's not this much of an issue, but still.
    Is there a good solution for a regularly changing state, that is needed by a bigger amount of components ?

  • @cool_scatter
    @cool_scatter Рік тому +1

    I wish I had seen this before spending a day adding Zustand to manage my server state.. rewrite time I guess

  • @afifdev
    @afifdev Рік тому +2

    Hi Theo, i'm always see your videos, i have a request for you, can you explain about SWR from vercel? and make a comparation between SWR and useQuery, which better?

    • @haidarezio
      @haidarezio Рік тому +1

      he made a livestream last night that talked about this

    • @afifdev
      @afifdev Рік тому

      @@haidarezio Whoa, ok noted that, thank you in advance, theo

  • @ashharkausar413
    @ashharkausar413 Рік тому

    Thank you for these instructive videos.

  • @PaulSebastianM
    @PaulSebastianM 11 місяців тому

    Amazing rundown of React state management even for beginners (1+ years)!

  • @name_less227
    @name_less227 Рік тому +2

    Loving the rants. This was helpful. I have a question.
    Say I'm making a query filter.. I was using jotai along with updating query params at the same time on every query change. Then I decided there is no point of using jotai and am using query params as the state. For instance, when the page is first loaded it reads the query params and applies to the select / dropdowns / etc. On any changes by the user, it directly updates the url query and then a useeffect forces a rer-ender.
    Just wondering if it is an option to only use query params as the local state in this case? Thanks.

    • @dealloc
      @dealloc Рік тому

      Depends. As long as it doesn't pollute the query params with unrelated state that has nothing to do with the specific page, and you want an easy way to hydrate your initial state, then use query params to hold the state.

    • @name_less227
      @name_less227 Рік тому

      @@dealloc Thank you. I don't think there will be any other params on the page besides those. What would be a better way to do it? Is it necessary to setQueryData on the queryclient at the same time, after every query change and initial page load?

    • @dealloc
      @dealloc Рік тому

      ​@@name_less227 I don't think I would use React Query to manage query params state, since query params should be the source of truth and reading/updating them is synchronous. React Query would just add another layer and complexity.
      I would write hooks that can sync with the query params, and if I needed the optimisation, have a way to select individual params to avoid unnecessary re-rendering from changes to unrelated params.
      React Query only really makes sense in contexts of asynchronous queries (fetching) and mutations (execution).

    • @archmad
      @archmad Рік тому

      It is a good way for filters, search, and with shareable urls. So you have to plan and decide these things ahead

  • @radhouze2554
    @radhouze2554 Рік тому +2

    Libs that do a bunch of magic for you in the background are HELL for bigger projects. Avoid suggesting React Query if you work on anything remotely big/complex

  • @hundehausen
    @hundehausen Рік тому +1

    Can you do a video about error handling with react query? fetch doesn't throw Errors, when the Sever Resonse Code is 404 for example, but axios does.

    • @haulin
      @haulin Рік тому

      const res = await fetch('/');
      if (!res.ok) throw new Error('fetch failed');
      This will be caught by the various onError handlers. I like to use a global one for mutationCache / queryCache that just displays a notification to the user.

  • @NeoChromer
    @NeoChromer Рік тому +5

    Needs more MobX

  • @guillaumehuardhughes1091
    @guillaumehuardhughes1091 Рік тому

    We were using context and we replace a lot with Zustand.
    It was easy and make a lot of thing easier and way more performant!
    Nice tech

  • @JorgeLuisMachadoTorres
    @JorgeLuisMachadoTorres Рік тому +3

    I'm still on the belief that redux toolkit polish the implementation and keeps the values of the single source of truth and immutability with less code and opinionated, which was the main issue for me the amount of boiler plate code

  • @SonAyoD
    @SonAyoD Рік тому

    Great video, thank you!

  • @tasin5541
    @tasin5541 Рік тому

    How would you use react query in applications where you post a bunch of data and get response from the api. then go to the next page, and use that returned value without passing any data between the pages?

  • @shawnradke
    @shawnradke Рік тому

    Did theo remove the folder structure rant he had?

  • @pallas6708
    @pallas6708 Рік тому

    do you share your notes on these kind of takes or rants. i would like to look around those notes if it's possible . Great content btw .

    • @t3dotgg
      @t3dotgg  Рік тому

      They’re available on my Patreon

  • @NicolasSilvaVasault
    @NicolasSilvaVasault Рік тому

    i just realize me and a colleague pretty much created a jotai eske state manager for our apps

  • @NikolajLepka
    @NikolajLepka Рік тому

    yo zustand is really cool
    thanks for showing it off!

  • @elenamikhaylova5086
    @elenamikhaylova5086 Місяць тому

    great explanation, i feel like i just leveled up as a UI dev

  • @benny-shen
    @benny-shen Рік тому

    Can I use multiple state management in the same project?

  • @nicolocardozo7699
    @nicolocardozo7699 2 місяці тому

    Nice video! Thank you! Can I ask you how would you persist the state of a React native app? Would you use the same stack?

  • @ibrahimmohammed3484
    @ibrahimmohammed3484 Рік тому +2

    I do have a use case where i need to store large amount of data in memory around array of 700k objects and multiple instances of the same dataset from reading files in the browser, had my experiments with the following libraries ranked by performance issues i have faced for such type of app:
    same codebase - same functions - same environment ( just replacing the state manager )
    Valito, dead simple but absolute trash performance (app crashes totally).
    Jotai, simple but laggy performance and hiccups in data loading.
    easy-peasy, simple, very friendly syntax, uses redux under the hood, amazing performance and devtools support but 9kb bundle size.
    Zustand, don't like the syntax but performance is solid and only 1kb bundle size.

    • @dealloc
      @dealloc Рік тому +1

      Storing 700k objects in memory within JS is a great indicator for optimization. At that point you should resort to storing it in IndexedDB and then retrieve a slice based on navigation, pagination or viewport (i.e. virtualized list). Store only what you need to show to the user in UI.
      In case you retrieve the data from a remote server, you should not send all 700k objects at once. Only store and fetch what is needed to render, because it can quickly result in poor UX both in terms of performance but also bandwidth, especially if those objects needs to be mutated as well.

    • @ibrahimmohammed3484
      @ibrahimmohammed3484 Рік тому

      @@dealloc although i haven't played with indexdb or other browser based storage before but thanks for pointing them out but unfortunately this app is a visualization app which actually needs the full dataset to be available all at once and the app would even handel far more objects of data or multiple instances of the same dataset.
      Zustand handles it just fine, redux based solutions but for sure you can't run away from actual memory usage bounds for the user hardware. Just thought it's a good example to put someone in perspective about some of the state managers I've used.

  • @wateenafzal2963
    @wateenafzal2963 Рік тому

    If we have t3stack implemented in for a complex SaaS app what works best for state management...jotai or zustand for making sure that we are type safe....and if we use both to manage events and global state as stated...how would such an implementation look like

  • @bench2328
    @bench2328 Рік тому

    Is it wrong to be using the local storage API to manage state?

  • @PelFox
    @PelFox Рік тому

    When you mutate with react query. Let's say your PUT request returns the updated entry and you have a list of 100 items.
    It makes little sense to re-fetch all 100 because you updated one right? Using a traditional client state management you would use spread operator and just update one entry.
    So, do you still invalidate the cache fetching all items or do you just update it manually yourself in the OnSuccess?

    • @t3dotgg
      @t3dotgg  Рік тому +2

      What you’re looking for is called an “optimistic update” - very easy to do in RQ!

    • @PelFox
      @PelFox Рік тому

      @@t3dotgg thanks for the fast reply. I just looked up on it and it looks good using as it also has supports for rollback father than refetch if mutation failed.

  • @Andreas-gh6is
    @Andreas-gh6is Рік тому +21

    If you think redux is in your way, you're doing it wrong. RTK has reduced a lot of the boilerplate. RTK Query is just as easy to use as React Query, with actually the same mechanics, but works not just in components, but also in async workflows. The problem I see with hooks-based API calls is that this can lead to a very intransparent async workflow based around when components are visible or not. In my opinion, using chains of useEffect for defining these flows is an antipattern. That's where thunks and sagas come in. Thunks are easier to understand than sagas and allow you to have more complex state flow altogether in a few lines. Sagas are even better because they allow you to react to things happening in the app. You can use them for "autostart" behavior, for situations where you want certain data fetched/refetched when the route changes, I've used them to auto-scroll when new data comes in. Sagas are also the easiest async abstraction to unit test because you only need POJOs to mock everything from server responses to user interaction. The next important component are selectors using "reselect". "createSelector" allows you to structure your computed state in a principled way. They are memoized. They can be composed easily. I have selectors that pick out only part of a state structure. I have selectors that enrich the state with precomputed values. I have selectors that create non-primitive objects out of primitive state (rehydration). RTK Query comes with selectors for each query. I can combine selectors from multiple queries. I can use selectors in components, thunks and sagas. Having the "computed state" logic in the selectors means a lot less JSX salad. And redux is almost trivial to unit test. Most of the time, you don't need a fully filled out state to test reducers, action creators, selectors and so on. Pure functions are easy to test and by just specifying the data the specific functions will need allows me to assert assumptions about the code. In my opinion redux is still the best way for state management.

    • @zavarka2
      @zavarka2 Рік тому +2

      100%! Using React Query violates the SOLID design principles and makes unit testing very difficult.

    • @rprLKA
      @rprLKA Рік тому +2

      I see lots of personal opinions, rather than actual facts in this channel.

    • @randomlyswatching9481
      @randomlyswatching9481 Рік тому

      I say this too
      We have the exact setup in prod but i don't see redux is going away anytime soon . I'll still try others in my pet projects

  • @nomadtrails
    @nomadtrails Рік тому +1

    Jotai and Zustand look good. We use Svelte and therefor get Svelte Stores, which are one of the strongest selling points of Svelte. Glad to know I can work this way in React in the future if I have to.

    • @BosonCollider
      @BosonCollider Рік тому

      Preact signals are another great alternative for jotai

  • @pedropereira3270
    @pedropereira3270 Рік тому +2

    Valtio or Zustand are my go to for state.

  • @jelooJusta
    @jelooJusta Рік тому

    I'm using react-query for APIs and hookstate for the rest global state management. Still have to use redux on legacy projects

  • @klemenko345
    @klemenko345 Рік тому

    Can you do an explanation of why not use vue / when to use it... etc.
    I personally hate how vue looks like (code, setup ...), but I don't think that is a good reason to not use a framework.
    thoughts?

    • @t3dotgg
      @t3dotgg  Рік тому

      Vue's fine! I don't like the magic strings and SFC's personally but there aren't many things where you should "100% use react and not Vue" (except for React Native)

  • @O_Eduardo
    @O_Eduardo Рік тому +3

    I think I have to udpate my notion on what is "simple". Because the example shown using that react-query library doesn't fell right.
    I fell like everything today must be very tight coupled with the framework or library. In my understanding, every server fetching is a service, I delegate to a folder called services that contains a set of vanilla javascript functions that will fetch, reshape the structure, format values and send it back to whoever is calling it. No "useSomething" is required. Just a simple {getUser, getUsers, etc } from service/user. No magic envolved, less learning curve to newcomers, less library to learn in onboarding.
    This is one of the concepts I actually agreed with Uncle bob, you should push to the end of your layers the details of your implementations and also create adapters, factories to plug in your component logic level. React is a UI library and ts awesome when you use it only for updating ui state, and that's it. I have been benefited with this kind of mentality especially on migrations I've participated where everything that was write in vanilla was ported to the next framework or the next framework version just moving folders. The service layer should be a black box where it will have the same behavior with vue, react, angular, vanilla js etc. Promises are very strong and have very powerfull way to compose.
    For me, we only need a a state managment abstraction to deal with application logic and state transitions, the ui changes and event listeners should be adressed to your UI framework, and external async data should be delegated to a set of async functions where your component might use it by composition. Maybe I would write a ui component that automate that loading / error / success, in case of react it can be a hook that returns methods and a wrapper component, but it's just a few lines of code...
    I also wouldn't tight front end with back-end in order to automate the process of updates, for me that makes the system more weak. Front-end should be ready to integrate with any shape of api's and the logic that abstracts that I believe it should be in the services layers, using adapters, middlewares or brigde or any kind of well known and simple technics working since 60's.
    I wouldn't say that react-query is useless, it probably have its space... but I'm going to my 15 year now with js in client side applications and ... That's not the kind of thing that helps in the majority of the real problems I've faced... It's just a distraction.

    • @t3dotgg
      @t3dotgg  Рік тому +4

      "maybe I would write a ui component to automate that loading/error/success"
      I dare you to try. Make it even HALF as ergonomic as React Query and you might have a startup on your hands.
      The first half of this comment ignores the 'many states around async' entirely. The second half brushes them off like they're trivial additions. You may have a lot of JS experience, but it doesn't sound like you've built a lot of interactive user experiences with them

    • @O_Eduardo
      @O_Eduardo Рік тому +1

      @@t3dotgg
      I really respect your thoughs man, don't get me wrong.
      I used to hear things like that: "You might not have a lot experience on this", "Maybe you havent work on a project on this size" etc. It's pretty much clear to me what is difficult and what is not in front end. I believe that most of the things are just distraction and over engineering is more often than it should. I think there's a sense that a case shown by an ex fang engineer is the way of solving the majority of the problems we have.
      But often time proofs what I'm saying through these years, I remember to list some issues about React design and what I thought it should be reconsidered and I got the same responses like: You don't know what your saying, you don't have the experience on this and so on. The fact is that all of those list I've discussed before doesn't exists anymore in React Development. It took more time than it should to people understand how bad it was, the discussion was focused on other minor things. The same thing happens with SPA's vs SSG and SSR era...
      I worked on several refactories and rebuilding apps that someone once told that it wouldn't be possible if we wasn't using : Angular, Redux Saga, RXJS, Rambda etc etc... The reality is that I was able to do the same thing, with a half of the code, indirections and libraries.
      I'm from another time, where I had to implement myself Charts, Zooming, drag n drop, Sliders, animations and easings, those things still give me creeps, we already have many solutions for all of them today, and kinda can predit the behavior across browsers. I think that Browser, Tools, Language, Ui Libraries gets better very fast relatively speaking, but I really don't think that the majority of "applications" got complex in the same pace. we do have more complex applications today but we also have good abstractions/patterns to deal with them.
      I think I'm pretty aware about how dificult a front end application can be knowing about what browser is capable of and its restritions and contrains, I found pretty hard to make a web page doing something completely out of this world, with exception of WebGL. To find a super hiper complex web page as an example might not be acurate, I'm talking about those others 99%.
      But you might be right, I'm might not have that experience with user interfaces, but I'd like to give the benefit of doubt because I'm genuinely looking for something that invalidates my theory, I kindly ask you to share some app as a reference so I can update my understanding regarding those abstractions.

    • @saritsotangkur2438
      @saritsotangkur2438 Рік тому +1

      The point of frameworks is to gain some form of DX improvement. Abstracting that away seems counter-productive. Perhaps you’re only doing that because the framework is being pushed upon you and not because it’s what you want to use.

  • @CodingWithChaim
    @CodingWithChaim Рік тому +1

    Why would we not be able to break up context in the same way we would break up our atoms using Jotai? This way only the components consuming the changing context would re-render. If breaking things up into smaller pieces is the strength of Jotai, it would seem that react context has that same possible benefit

    • @t3dotgg
      @t3dotgg  Рік тому +2

      Contexts have to wrap your app, atoms exist outside of it. There are some hacks to get similar experiences w/ context, such as useSelectFromContext (which was made by the same person as Jotai)

  • @BenniK88
    @BenniK88 Рік тому

    Is react query also working well together with firebase or does it only work well with classical fetch()?

    • @t3dotgg
      @t3dotgg  Рік тому +1

      As much as I dislike Firebase, it will work great for that

    • @mjohnson510
      @mjohnson510 Рік тому

      They literally have a react-query-firebase library that supports the built in queryDevtools and comes out of the box with all the APIs you need. *Some are missing but… who cares!*

    • @BenniK88
      @BenniK88 Рік тому

      @@t3dotgg Thanks! Ok I will give it a go. I will use the regular „$ npm i @tanstack/react-query“ instead of the „npm i --save @react-query-firebase/firestore“ Package as I‘m not sure how well maintained the on top abstraction is and is says there are some functions missing. And in addition in worscase I then have theee packages instead of one. Firebase, react query and react-query-firebase. Would you agree to that choice? Also if you dislike Firebase you should do a video about it 😊 and tell what you prefer in exchange! Cheers

  • @Nosleepguy
    @Nosleepguy Рік тому

    Without zustand base on redux but its make me feel too easy to use. I love zustand a lot

  • @MrDima123123
    @MrDima123123 Рік тому +2

    Why not MobX instead of those?

  • @swikarsharma3118
    @swikarsharma3118 Рік тому +2

    i was using valtio state management and it seems insane

    • @imornar
      @imornar Рік тому

      Yeah, valtio is super sweet, I fell in love with it

  • @Liz3_
    @Liz3_ Рік тому +3

    redux us very verbose yes, but points in this video like zustand to be used outside of react are easily doable with redux.
    what i like about redux is the way it handles updates which can be n to n.
    a action can update 1 reducers or 60.

  • @zsambokiattila9765
    @zsambokiattila9765 Рік тому +2

    I am a junior engineer and I cant belive what I am seeing...

  • @ESArnau
    @ESArnau Рік тому +1

    What about useReducer instead of zustand?

  • @GGGGGGGGGG96
    @GGGGGGGGGG96 Рік тому +4

    This is a nice introduction to React Query. The idea behind React Query is very nice and it is going the right way, but React Query comes with other problems. It is hard to explain it here, but in short: In all these tutorials with a simple todo-list, React Query looks amazing. But in reality on big projects, where you maybe have a lot of list-views and re-usable functions like "mark-user-as-favorite" (for example) and you need to write mutate-functions, React Query can be a nightmare.

    • @killerdroid99
      @killerdroid99 Рік тому

      exactly even for voting a single post on lets say a blog site I have to forcefully invalidate every post assuming the app uses SSR

    • @GGGGGGGGGG96
      @GGGGGGGGGG96 Рік тому

      @@killerdroid99 To solve this problem, I use an event-driven-system. So on a post-voting-action, i would dispatch an "post:voting"-event (or something like that). The lists just listening to this event and mutating their data. For mutating-operations, because they are really ugly in ReactQuery, I use a helper-function where I just pass the list-key, object-id, property-name and value. So sadly it is a lot work.

  • @vnm_8945
    @vnm_8945 Рік тому

    bery cool, I knew about Recoil, didn't know about Jotai and Zustand, subscribed and will subscribe on Twitch, too.

  • @CaleMcCollough
    @CaleMcCollough Рік тому

    I'm working towards the Script2 React State manager but I need C++ volunteers first. The Chinese Room Abstract Stack (Crabs) Machine that powers Script2 can be in any language.

  • @RossPfeiffer
    @RossPfeiffer Рік тому

    D.o.D. engineer chiming into t3 for tech tips

  • @davorinrusevljan6440
    @davorinrusevljan6440 Рік тому +1

    I'll certainly look into that, but at first: why would I use/learn 3 more things instead of redux?

  • @omri9325
    @omri9325 Рік тому +1

    Did I miss the part where Mobx was mentioned?

  • @JohnnyNguyen
    @JohnnyNguyen Рік тому

    that's the really little debugging bro :D

  • @noone-gz4pc
    @noone-gz4pc Рік тому

    anyone know what vscode theme is this? this looks awesome

  • @tesilab994
    @tesilab994 Місяць тому

    State machines (e.g. XState) fullfill a different function from state managers like redux that apply reducers. State machines consume events and potentially transition. Associating behavior with entering/exiting states, or with a specific transition can generate new events. Also XState's configuration is much more complicated than it needs to be to represent a set of states and transitions, I instantiate them from more concise notations that would make a statemachine your goto choice even if you only want to replace a timer and an if statement or two. That is because they are airtight, logic wise. And you totally separate state transition logic from transition behavior.

  • @maleksmida2464
    @maleksmida2464 Рік тому +24

    you may consider RTK query developed by Redux toolkit team, that replaces react query if you are using Redux toolkit

  • @nymusicman
    @nymusicman Рік тому

    25:33 I wonder how hookstate js would compare with something like jotai.

  • @owenwexler7214
    @owenwexler7214 Рік тому +1

    Me before watching this: "wtf kind of name for a state management library is Jotai"
    Me after watching this: "Seriously considering switching my web app's global state from Context to Jotai"

  • @danielhodapp8703
    @danielhodapp8703 Рік тому +8

    Rtk & rtk query are a strong combination for production apps. Maybe have a look.

    • @Krzysiekoy
      @Krzysiekoy Рік тому +4

      Yeah, RTK Query is really good.

    • @SeanLazer
      @SeanLazer Рік тому +1

      I've been using RTK-Query for about a year but I may migrate to React Query. I see hardly anyone talking about RTKQ which means a lot more open source effort is going into RQ.

  • @razbensimon2
    @razbensimon2 Рік тому

    Where MobX solution fit in your diagram?
    And what your thoughts about it?

  • @mariansam_was_taken
    @mariansam_was_taken Рік тому +1

    How about GraphQL with Apollo Client in React Native? I guess Apollo Client is comparable to React Query in this context..?

    • @dealloc
      @dealloc Рік тому

      Apollo Client comes with a lot of headaches for small projects (and even worse in larger applications), and alternatives like urql is worth looking into. For larger applications with more data requirements, Relay is also an excellent way to handle your GraphQL. Albeit it coming with a steep learning curve, it also provides a great UX, since it's easy to co-locate your data requirements with your components.
      React Query is agnostic to any async operation for querying (fetching) and mutations (execution) but may required abstractions to get the same benefits as GraphQL-specific clients with the same ease of use. I would choose a library that fits my needs, if available or build something on top of React Query, since it comes with tooling for free.

    • @killerdroid99
      @killerdroid99 Рік тому

      @@dealloc react query kinda supports graphql

    • @dealloc
      @dealloc Рік тому

      @@killerdroid99 Since GraphQL is just a format, anything that can make HTTP request can interface with a GraphQL endpoint. However, urql and Relay provides specific APIs for dealing with GraphQL mutations, queries and subscriptions, caching, code generation and much more out of the box.
      I'm not saying you can't use React Query with GraphQL, but as your app grows you'll end up writing your own abstractions that you have to maintain.

  • @sadique_x_
    @sadique_x_ 4 місяці тому

    i couldn't make this guy out in 2024, the moustache

  • @Vicky-wj7vw
    @Vicky-wj7vw Рік тому

    In an atomic state we can only have one state with the use of an atom family this will not rerender your all data and components.

  • @danailenei9959
    @danailenei9959 Рік тому

    I think it is the first time when I actually subscribed at the end when some video reminds me to