STOP using useState, instead put state in URL (in React & Next.js)

Поделиться
HTML-код
  • Опубликовано: 27 май 2024
  • Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).
    👉 Add auth to your app FAST: bit.ly/3QOe1Bh
    👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
    👉 Professional JavaScript Course: bytegrad.com/courses/professi...
    👉 Professional CSS Course: bytegrad.com/courses/professi...
    👉 Discord: all my courses have a private Discord where I actively participate
    🔔 Email newsletter (BIG update soon): email.bytegrad.com
    ⏱️ Timestamps:
    0:00 Examples
    0:41 Benefits
    2:38 Example overview
    4:24 useState
    6:56 Synchronize URL with useEffect
    7:30 History API
    7:54 Query string definitions
    8:58 Next.js useRouter
    10:20 location.search
    11:18 Problems with useState approach
    11:58 Switch to URL for state
    12:26 useSearchParams
    13:35 Link component
    16:11 Server component (searchParams)
    17:13 Caveat 1: replace vs push
    17:57 Caveat 2: unknown values
    18:18 Caveat 3: no values
    18:32 Caveat 4: url-encoded values (URLSearchParams)
    20:47 Real-world use cases
    #webdevelopment #programming #coding

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

  • @alexnelson2119
    @alexnelson2119 6 месяцев назад +32

    A note about replace vs push, the Link component takes a `replace` prop that you can set to true (default is false) if you want the replace behaviour. It also has a `scroll` prop that you should set to false (default is true) if you don't want to scroll to the top of the page each time you click on an option.

  • @dimitrisborbotsialos
    @dimitrisborbotsialos 8 месяцев назад +112

    We’ve actually used this technique 4 years ago on a react application, worked great and still does. We’ve also made a search component to listen for changes on the url and update a context. Our app was complex and many components had to be updated so using a context was the way to go. It’s funny though that no matter what we do we always coming back to 00’s concepts. It’s like php back in the days.

    • @Diegps
      @Diegps 8 месяцев назад +5

      it's php with a mint flavor and I'm here for it

    • @spicynoodle7419
      @spicynoodle7419 8 месяцев назад +5

      Modern PHP with HTMX is the dream and I'm living it

    • @billypentester
      @billypentester 8 месяцев назад +4

      It depends on the requirements. If you're developing apps that don't share data like admin panels, use states and react. But if you're developing sites that do share data like e-commerce websites, use params and next js.

  • @samyakpiya
    @samyakpiya 7 месяцев назад +11

    You are so good at teaching web dev. I love that you show how something can be done with just JS and then proceed to show how a framework like Next.js makes it much simpler! Also, I really appreciate that you cover the edge cases and best practices. I'm learning a lot from watching your videos!

  • @webdev_telugu
    @webdev_telugu 8 месяцев назад +81

    Such a niche concept and he teaches us for free even though he has paid courses. Kudos my man!!

    • @ByteGrad
      @ByteGrad  8 месяцев назад +3

      Thanks

    • @RealRatchet
      @RealRatchet 8 месяцев назад +33

      It's not a niche concept putting stuff in query parameters was how Web1.0 did things because there was no client state, we've officially come full circle.

    • @shrin210
      @shrin210 8 месяцев назад +3

      ​@@RealRatchetNow we write in components and not in pages.
      That's the only thing changed from Web 1.0

    • @webdev_telugu
      @webdev_telugu 8 месяцев назад

      @@RealRatchet yeah true, but I'm a new developer so new thing to me

    • @henriquematias1986
      @henriquematias1986 8 месяцев назад +2

      What you mean niche concept? That’s how the internet works and always worked 😊
      It’s just that some websites are broken so he’s teaching how to fix it 😅

  • @saadelfadil
    @saadelfadil 4 месяца назад +3

    I stumbled upon your RUclips channel just today and had to reach out immediately to express my gratitude for the incredible content you’re sharing. Even though it's only been a day, I've already spent hours soaking in your insights. The way you explain concepts is nothing short of amazing 🔥🔥

  • @maisamafshar
    @maisamafshar 8 месяцев назад +3

    Excellent presentation and explanation. Loved the pace of the video, not slow, not fast. Subscribed.🤩

  • @developerpranav
    @developerpranav 8 месяцев назад +42

    This is awesome with server components! Very detailed video that includes URL encoding and search params. Waiting for your nextjs course :D

    • @ByteGrad
      @ByteGrad  8 месяцев назад +1

      Thanks! 😃

  • @LePhenixGD
    @LePhenixGD 8 месяцев назад +4

    Amazing tutorial man! Never had that idea to use URL parameters not for a search but for products until now, thank you!

  • @lets_see_777
    @lets_see_777 6 месяцев назад +4

    somehow your teaching method resonates best with me. There are several popular youtubers on JS but you explain why we are doing things with alternatives. Thank you.

  • @coffeefps
    @coffeefps 8 месяцев назад +5

    This is actually clean and good. Just need to handle the magic strings gracefully and it's perfect.
    You earned my sub.

  • @ebratz
    @ebratz 7 месяцев назад +1

    This tip saved me a lot of time today! Thank you so much! Eager waiting for your Next.js course!

  • @simoncunningham2964
    @simoncunningham2964 21 день назад +1

    Thank you for this video - I've watched a lot of tutorials lately that go down the route of useState and useEffect but they never felt like the best way - glad I came across this video!

  • @silentlyow
    @silentlyow 8 месяцев назад +5

    I recently started a project on a brand new framework recently (Next.js) with TypeScript as well (first typescript experience as well) and discovered this method of handling something like "state" in server components. Basically I had a product page and needed to do pagination and filtering, I did it using the query string.

  • @saitharunreddya2046
    @saitharunreddya2046 8 месяцев назад +1

    An awesome video with great details and explanation, loved it!!! Keep Up the good work

  • @seg_fault
    @seg_fault 6 месяцев назад +1

    Thanks for the video. I heard of this and needed to see an example of how to go about it and this went above and beyond with even the pitfalls to watch out for.

  • @foreverl01
    @foreverl01 8 месяцев назад +22

    I found your videos last week and I've seen more than 10 hours of your content. The way you explain things is amazing. Thanks, Wesley!
    I'm making an e-commerce myself to practice react and next.js, using app router. This solution to avoid using state and making components CC is great!
    I can't wait for the next js course!! 🥳

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Awesome, thank you!

  • @guilhermeferreirabr
    @guilhermeferreirabr 8 месяцев назад +4

    Dziękuję bardzo za tutoriale, właśnie kupiłem dwa twoje kursy, niesamowita treść! 🚀👏🎬

    • @ByteGrad
      @ByteGrad  8 месяцев назад +2

      Thanks Guilherme! Appreciate it

  • @filipniklas
    @filipniklas 8 месяцев назад +2

    Great video! Super helpful and well presented!

  • @weebdeveloper
    @weebdeveloper 8 месяцев назад +1

    True, derived state makes some features so much simpler to build, thanks for sharing

  • @Olga-id1qy
    @Olga-id1qy 6 месяцев назад +1

    Beautiful, it made me smile for a sec as I would write it exactly as you mentioned at the beginning via useEffect(). Now while transitioning to Next.js, I like definitely this one-way approach

  • @kevin-ty7it
    @kevin-ty7it 8 месяцев назад +2

    I have a short attention span, but you shared information continuously, which kept me engaged throughout.

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

    I love you. You’re an awesome teacher. I’m grateful to have found your channel 🙏🏻

  • @James-rd1sb
    @James-rd1sb 8 месяцев назад +1

    I never thought of it like this. I'm sure it'll be useful to know in the future! Many thanks

  • @pi3ni0
    @pi3ni0 6 месяцев назад +1

    Thanks, very good content. A lot of real world cases, can't wait for your course! :)

  • @mu_yaser
    @mu_yaser 8 месяцев назад +1

    wanted to use this concept in my latest next project and you just explained things i needed to know, good info and explanation

  • @Anonymousssss368
    @Anonymousssss368 8 месяцев назад +2

    The content was amazing. I used this approach in my project.

  • @vikasni95
    @vikasni95 8 месяцев назад +2

    Im very lucky to find your channel on random search.. Tq god for suggesting this gem channel... Tqss dude keep adding more videos 😍👍

  • @Scrappycoco
    @Scrappycoco 8 месяцев назад +1

    Great content man. Keep it up!

  • @ganumba11
    @ganumba11 8 месяцев назад +1

    amazing content from you like always 🔥🔥

  • @i.j.5513
    @i.j.5513 8 месяцев назад +1

    Very nicely explained and demonstrated 👍

  • @user-ge2vc3rl1n
    @user-ge2vc3rl1n 8 месяцев назад +1

    This is a very cool and unique example, looking forward to more. GJ

  • @NOTHING-en2ue
    @NOTHING-en2ue 8 месяцев назад +1

    very well tutorial, you finally teach me how to think the next-js way ❤

  • @ardianhotii
    @ardianhotii 8 месяцев назад +1

    This video was very helpful, I'm learning so many new things from you that I didn't know that can cause problems in my apps. Thank you so much

  • @taicheeeee
    @taicheeeee 8 месяцев назад +1

    Best youtubers for beginngers: Lama Dev, and Net Ninja
    Best youtuber for junior and middle developers: YOU

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Haha thanks

  • @MOURADSLIM
    @MOURADSLIM 8 месяцев назад +1

    I'm doing a search function and was gonna use a state manager to manage this problem, perfect timing XD
    Thank you

  • @OpenCoreX
    @OpenCoreX 8 месяцев назад +1

    This is just amazing. Glad I discovered you - amazing teacher. #subscribed

  • @nomadshiba
    @nomadshiba 8 месяцев назад +2

    not using react or next, or tsx
    but this is so true!
    especially for modals, i like to keep my active modal info on the hash part of the url
    that way both page data and modal data can be placed on the url
    but of course you can use url params too
    i mean you realize that your site/app needs this the moment you refresh the page

  • @igboanugwocollins4452
    @igboanugwocollins4452 8 месяцев назад +1

    Neat approach, you just gained another sub

  • @WojciechBlachut
    @WojciechBlachut 8 месяцев назад +1

    That is an excellent video! Thanks so much.

  • @arinium
    @arinium 3 месяца назад +1

    You make absolutely great tutorials, thank you for sharing!

  • @andreilucasgoncalves1416
    @andreilucasgoncalves1416 8 месяцев назад +54

    Query strings are usually a lot harder to work with than useState, you have to validade the input to avoid errors, specially if you change things and the query data becames stale, but anyways query strings provides a great UX

    • @zettca
      @zettca 8 месяцев назад +14

      If your data/endpoint inferred from the searchParams, it won't become stale. searchParams should be the SSOT (single source of truth). And as these are user-controlled, there should be some validation - yes.
      A small validation function is the trade-off for the greater UX

    • @zettca
      @zettca 8 месяцев назад +8

      Another thing: we shouldn't be building the searchParams by hand anyways. There's URLSearchParams for that

    • @Kaioin
      @Kaioin 8 месяцев назад +13

      You should be validating data that you use with useState, too, if it comes from userland.

    • @wisdomelue
      @wisdomelue 8 месяцев назад +4

      everything has its tradeoffs

    • @CottidaeSEA
      @CottidaeSEA 8 месяцев назад

      Validation is always an issue and honestly, in a case like this it is simply absurd to expect query parameters to exist immediately. For these things you should always have a fallback.

  • @aamiramin6112
    @aamiramin6112 8 месяцев назад +1

    So informative. Thanks for sharing

  • @veedjohnson
    @veedjohnson 8 месяцев назад +2

    Definitely one of the best out there!

  • @oidualx
    @oidualx 7 месяцев назад +1

    Thank you so much! This way of handling state is nothing knew, but I personally never put much thought into it until this video, and always defaulted to client state, with all the issues you listed. Typical aha moment. From now on you convinced me to always default to query params to handle state, unless there is a serious reason not to do so.

  • @CuriousByte
    @CuriousByte 8 месяцев назад +1

    Always a super useful technique especially for UI's that you likely want to remember state when you copy and paste the link.

  • @mmaarafat
    @mmaarafat 6 месяцев назад +1

    thanks, mate. it was great explanation :)

  • @mohammedelmoutaouakkil
    @mohammedelmoutaouakkil 7 месяцев назад +1

    Great tutorial! you got a subscriber

  • @loydcose2780
    @loydcose2780 8 месяцев назад +1

    Amazing, super helpful!

  • @ChrisHaupt
    @ChrisHaupt 4 месяца назад +1

    That's a really cool trick using the Link component to append a query param. Didn't know that was a thing!

  • @ThugLifeModafocah
    @ThugLifeModafocah 8 месяцев назад +1

    Very good video. Thank you.

  • @codewithguillaume
    @codewithguillaume 8 месяцев назад +1

    Huge fan of this approach :)

  • @TitoMitto
    @TitoMitto 7 месяцев назад +1

    Your tutorials are very informative

  • @mohammadmo9290
    @mohammadmo9290 8 месяцев назад +1

    Amazing, thanks mate 👌👌

  • @DiogoLScarmagnani
    @DiogoLScarmagnani 6 месяцев назад +1

    Wow! I didn't know about History API and its pushState method. Great! It can be used even in vanilla JavaScript projects. Thank you for the video.

  • @glauberbispo8922
    @glauberbispo8922 8 месяцев назад +1

    mind blowing I always work with states, i'm looking foward to implement this solution in some of my works *-*
    and it works really good together with server side in next

  • @rubelhossain8517
    @rubelhossain8517 8 месяцев назад +4

    amazing content ! Keep up the good work sir

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Thanks, will do!

  • @billypentester
    @billypentester 8 месяцев назад +1

    It's really something great for me, actually, I'm looking for something similar to this concept and I got it. So much thanks sir

  • @kumardeepam
    @kumardeepam 8 месяцев назад +1

    This is so insightful and useful

  • @JosephMaramba
    @JosephMaramba 8 месяцев назад +3

    Pretty well explained. I didn't know server components get the searchParams as props by default!

  • @chrishanthacosta4093
    @chrishanthacosta4093 5 месяцев назад +2

    I find Wesley to be the best NextJS teacher.

  • @geianmarkdenorte9874
    @geianmarkdenorte9874 8 месяцев назад +1

    Just subscribed, I love your content man! I wish the audio can be improve soon.

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Yes, will improve soon. 2-3 more videos with this haha

  • @darwin2642
    @darwin2642 8 месяцев назад +1

    Thanks for this video, it helped me a lot.

  • @lorsothy6263
    @lorsothy6263 8 месяцев назад +1

    Thank you so much. Now I found a way to select filters without use client.

  • @user-qo6jf6jk2c
    @user-qo6jf6jk2c 8 месяцев назад +1

    many thanks for great content ❤

  • @mohamedbelaouer1696
    @mohamedbelaouer1696 8 месяцев назад +1

    I juste love your content. thank you for your useful videos

  • @raymondmichael4987
    @raymondmichael4987 8 месяцев назад +1

    I had similar use case today, pulled my hair for hours;
    Thanks brother 😊

  • @DerberAlter
    @DerberAlter 2 месяца назад +1

    thank you, this video helped me quite a lot

  • @johncaballero5463
    @johncaballero5463 8 месяцев назад +1

    Exactly what I need right now.

  • @lukas.webdev
    @lukas.webdev 8 месяцев назад +2

    Great video!! Thanks for sharing. 😉🔥

    • @ByteGrad
      @ByteGrad  8 месяцев назад +1

      Thanks for watching!

  • @bklynpeter
    @bklynpeter 7 месяцев назад +4

    Another amazing video. I do have a follow-up question: In your example, the page is a presumably dynamic route? How do we utilize those dynamic elements (again, in your example, 'product' and 't-shirt') at the same time we are accessing the query-params? Thanks as always!

  • @septiantonrezkirahmatulloh3837
    @septiantonrezkirahmatulloh3837 8 месяцев назад +1

    thank you, sir. from your knowledge. I am learned something new from this.

  • @romeorel1679
    @romeorel1679 8 месяцев назад +1

    Never knew you have had a RUclips channel. I discovered you from your CSS udemy course. Quality work.

  • @iBryanKops
    @iBryanKops 8 месяцев назад +1

    Thanks for this content broth

  • @Alex-bc3xe
    @Alex-bc3xe Месяц назад +1

    freaking smart way of making the state in the URL never crossed my mind smart ass shit.

  • @BK-qx3qf
    @BK-qx3qf 8 месяцев назад +2

    You got subscriber. Nice tutorial.

  • @juanhedderich
    @juanhedderich 8 месяцев назад +1

    That was awsome, ty man!!

  • @alirezagarshasbi6557
    @alirezagarshasbi6557 8 месяцев назад +4

    i was looking to make a seperate context for a boolean value as a side effect of another context state change, but with the abuse of url its free state across the app😁
    thank you

  • @shubhojeetbera
    @shubhojeetbera 7 месяцев назад +1

    This was great & easy 👌🏻

  • @thevasupodcast4561
    @thevasupodcast4561 8 месяцев назад +1

    I love your videos. Thank you!

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Glad you like them!

  • @mohammadshariarparvez669
    @mohammadshariarparvez669 7 месяцев назад +1

    watching your first video , became a fan of you broooooooo.. god bless you

  • @spacecowboyofficial
    @spacecowboyofficial 8 месяцев назад +2

    This just feels right. UX is more than just visuals when designing a website.

  • @HerrThomasE
    @HerrThomasE 8 месяцев назад +1

    thank you very much for this Great explanations,,!,,!!

  • @Imjoshnewton
    @Imjoshnewton 8 месяцев назад +1

    Love this solution for handling state especially when you want to set state down the tree and read it across other components. The issue I’ve run in Next 13 is setting the paean jumps you to the top of the page. Even when using replace…

    • @ByteGrad
      @ByteGrad  8 месяцев назад +1

      You can configure that on the Link component (set ‘scroll’ prop to false)

  • @dero433
    @dero433 8 месяцев назад +3

    Dzięki za porady!

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Bez problemu!

  • @ammaralshathry9186
    @ammaralshathry9186 8 месяцев назад +1

    really. incredible. keep up

  • @peterabouabsi8427
    @peterabouabsi8427 7 месяцев назад +1

    Depends on your case. This is a great practice for searching and fetching tasks.

  • @marchugans
    @marchugans 8 месяцев назад +5

    Great approach

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      I agree, underused by many devs

  • @runonce
    @runonce 8 месяцев назад +1

    Really helpful, thanks for sharing! I think the main con is that it only works for buttons as links and not for other types of inputs, I guess in that case you will still need to resort to a client component (I tried to use Server Actions but couldn't come up with a working solution).

  • @saputrauta09
    @saputrauta09 7 месяцев назад +1

    Thankyou so much!

  • @peteregbujie
    @peteregbujie 8 месяцев назад +1

    I cant thank you enough for this tutorial.

  • @stephenngeorge
    @stephenngeorge 8 месяцев назад +2

    This is a really great video :) and super interesting. I know it's nothing to do with the video but the "JavaScript magic" to make the first letter uppercase on those buttons is just "text-transform: capitalize;" in CSS 👍

    • @redeemr
      @redeemr 6 месяцев назад

      or since he's using tailwind just className="capitalize"

  • @fulltimefrontend
    @fulltimefrontend 7 месяцев назад +1

    We actually use this trick since 3 years in our React apps as well.

  • @zay-1x
    @zay-1x 4 месяца назад +1

    This video mention the way which i implemented before. Confirm that this way is really effecient and quite clear

  • @404-not-found-service
    @404-not-found-service Месяц назад +1

    Thanks for the video, I liked it a lot, will you by any chance upload more material like this also using useOptimistic and so on? all the best

  • @AndersonSousa33
    @AndersonSousa33 8 месяцев назад +2

    Your videos are awesome! Just need to raise the audio volume a little bit.

  • @nascob
    @nascob 8 месяцев назад +8

    It's a great tutorial. Nice pros and good pacing with good examples.
    A bit of constructive feedback - I think you're missing several important points.
    1) Validation - treating the URL as a single source of truth is fine - however it's super easy to mangle, incorrectly enter or purposefully break the URL - would have loved to see some patterns to deal with that. (as a side note - putting `as string` is not asserting anything - it's just telling typescript to ignore the fact that the URL param can actually be an array type)
    2) Async examples - in your case - setting the attributes for the t-shirt (esp. on the server side) is straightforward. However if you have a more complicated example where the product details are being retrieved from a database - it gets tricky to validate and apply the URL params against a dynamically set object. Also need to handle resyncing the URL if they are invalid.
    While the pros are good - there are some cons to this that become obvious with advanced usage.

    • @ByteGrad
      @ByteGrad  8 месяцев назад +3

      Yes, great points, thanks for sharing!

  • @nick-ui
    @nick-ui 8 месяцев назад +3

    Hey! I really glad to see that someone show this method to handling state in url, but this solution has potential disadvantage. It's animations. It's harder control when they're removed from the React tree. So when I use Framer motion, I can't make nice animations. Maybe vanilla css will, idk

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      Interesting, thanks for sharing

  • @iamnguyenhoanganh
    @iamnguyenhoanganh 3 месяца назад +1

    great video, thank you

  • @johnnyholiday1150
    @johnnyholiday1150 8 месяцев назад +3

    Hi 👋 I was wondering if its possible to please make a little/medium project with the most important points you showed in your vids. Would really appriciate it! 😁

  • @alexkey9372
    @alexkey9372 8 месяцев назад +3

    Great video! but what if the use case is to select something and change the api response? e.g a filter page. don't you need useEffect for that? you will need the filter params first from the actual api and then when url changes it needs to re-fetch the actual response from the api with the new variables via rest or graphql. like fetching products with an array of size selections and an array of colour selections. where the fetch function will need to be?