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

2024 ж. 17 Мам.
188 801 Рет қаралды

Hi, I'm Wesley. I'm a brand ambassador for Kinde. I'll help you master the latest tech here:
👉 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

Пікірлер
  • 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.

    @alexnelson2119@alexnelson21196 ай бұрын
    • Yeah, good points

      @ByteGrad@ByteGrad6 ай бұрын
    • Arigato

      @kamehameha38@kamehameha38Ай бұрын
  • 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.

    @dimitrisborbotsialos@dimitrisborbotsialos8 ай бұрын
    • it's php with a mint flavor and I'm here for it

      @Diegps@Diegps8 ай бұрын
    • Modern PHP with HTMX is the dream and I'm living it

      @spicynoodle7419@spicynoodle74198 ай бұрын
    • 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.

      @billypentester@billypentester8 ай бұрын
  • This is awesome with server components! Very detailed video that includes URL encoding and search params. Waiting for your nextjs course :D

    @developerpranav@developerpranav8 ай бұрын
    • Thanks! 😃

      @ByteGrad@ByteGrad8 ай бұрын
  • Such a niche concept and he teaches us for free even though he has paid courses. Kudos my man!!

    @webdev_telugu@webdev_telugu8 ай бұрын
    • Thanks

      @ByteGrad@ByteGrad8 ай бұрын
    • 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.

      @RealRatchet@RealRatchet8 ай бұрын
    • ​@@RealRatchetNow we write in components and not in pages. That's the only thing changed from Web 1.0

      @shrin210@shrin2108 ай бұрын
    • @@RealRatchet yeah true, but I'm a new developer so new thing to me

      @webdev_telugu@webdev_telugu8 ай бұрын
    • 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 😅

      @henriquematias1986@henriquematias19868 ай бұрын
  • 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!

    @simoncunningham2964@simoncunningham296410 күн бұрын
  • 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!

    @samyakpiya@samyakpiya6 ай бұрын
  • The good old PHP days

    @amansarma417@amansarma4178 ай бұрын
  • Excellent presentation and explanation. Loved the pace of the video, not slow, not fast. Subscribed.🤩

    @maisamafshar@maisamafshar8 ай бұрын
  • I stumbled upon your KZhead 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 🔥🔥

    @saadelfadil@saadelfadil3 ай бұрын
  • Amazing tutorial man! Never had that idea to use URL parameters not for a search but for products until now, thank you!

    @LePhenixGD@LePhenixGD8 ай бұрын
  • This is actually clean and good. Just need to handle the magic strings gracefully and it's perfect. You earned my sub.

    @coffeefps@coffeefps8 ай бұрын
  • This just feels right. UX is more than just visuals when designing a website.

    @spacecowboyofficial@spacecowboyofficial7 ай бұрын
  • Great video! Super helpful and well presented!

    @filipniklas@filipniklas8 ай бұрын
  • 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.

    @lets_see_777@lets_see_7775 ай бұрын
  • An awesome video with great details and explanation, loved it!!! Keep Up the good work

    @saitharunreddya2046@saitharunreddya20468 ай бұрын
  • I find Wesley to be the best NextJS teacher.

    @chrishanthacosta4093@chrishanthacosta40935 ай бұрын
  • 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.

    @silentlyow@silentlyow8 ай бұрын
  • This tip saved me a lot of time today! Thank you so much! Eager waiting for your Next.js course!

    @ebratz@ebratz7 ай бұрын
  • 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!! 🥳

    @foreverl01@foreverl018 ай бұрын
    • Awesome, thank you!

      @ByteGrad@ByteGrad8 ай бұрын
  • wanted to use this concept in my latest next project and you just explained things i needed to know, good info and explanation

    @mu_yaser@mu_yaser8 ай бұрын
  • Very nicely explained and demonstrated 👍

    @i.j.5513@i.j.55138 ай бұрын
  • 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

    @alirezagarshasbi6557@alirezagarshasbi65578 ай бұрын
  • True, derived state makes some features so much simpler to build, thanks for sharing

    @weebdeveloper@weebdeveloper8 ай бұрын
  • I have a short attention span, but you shared information continuously, which kept me engaged throughout.

    @kevin-ty7it@kevin-ty7it8 ай бұрын
  • Great content man. Keep it up!

    @Scrappycoco@Scrappycoco8 ай бұрын
  • The content was amazing. I used this approach in my project.

    @Anonymousssss368@Anonymousssss3688 ай бұрын
  • I never thought of it like this. I'm sure it'll be useful to know in the future! Many thanks

    @James-rd1sb@James-rd1sb8 ай бұрын
  • 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.

    @seg_fault@seg_fault6 ай бұрын
  • 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

    @andreilucasgoncalves1416@andreilucasgoncalves14168 ай бұрын
    • 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@zettca8 ай бұрын
    • Another thing: we shouldn't be building the searchParams by hand anyways. There's URLSearchParams for that

      @zettca@zettca8 ай бұрын
    • You should be validating data that you use with useState, too, if it comes from userland.

      @Kaioin@Kaioin8 ай бұрын
    • everything has its tradeoffs

      @wisdomelue@wisdomelue8 ай бұрын
    • 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.

      @CottidaeSEA@CottidaeSEA8 ай бұрын
  • Dziękuję bardzo za tutoriale, właśnie kupiłem dwa twoje kursy, niesamowita treść! 🚀👏🎬

    @guilhermeferreirabr@guilhermeferreirabr7 ай бұрын
    • Thanks Guilherme! Appreciate it

      @ByteGrad@ByteGrad7 ай бұрын
  • Definitely one of the best out there!

    @veedjohnson@veedjohnson8 ай бұрын
  • Best youtubers for beginngers: Lama Dev, and Net Ninja Best youtuber for junior and middle developers: YOU

    @taicheeeee@taicheeeee8 ай бұрын
    • Haha thanks

      @ByteGrad@ByteGrad8 ай бұрын
  • this guy is the best tech youtuber ever

    @perraanal@perraanal4 ай бұрын
  • amazing content from you like always 🔥🔥

    @ganumba11@ganumba118 ай бұрын
  • Im very lucky to find your channel on random search.. Tq god for suggesting this gem channel... Tqss dude keep adding more videos 😍👍

    @vikasni95@vikasni958 ай бұрын
  • This is a very cool and unique example, looking forward to more. GJ

    @user-ge2vc3rl1n@user-ge2vc3rl1n8 ай бұрын
  • Thanks, very good content. A lot of real world cases, can't wait for your course! :)

    @pi3ni0@pi3ni06 ай бұрын
  • I love you. You’re an awesome teacher. I’m grateful to have found your channel 🙏🏻

    @jou3883@jou38836 ай бұрын
  • very well tutorial, you finally teach me how to think the next-js way ❤

    @NOTHING-en2ue@NOTHING-en2ue8 ай бұрын
  • 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

    @ardianhotii@ardianhotii8 ай бұрын
  • 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

    @Olga-id1qy@Olga-id1qy6 ай бұрын
  • I like to keep state in the URL and use links + server components to make it work without JS

    @codinginflow@codinginflow4 ай бұрын
  • Pretty well explained. I didn't know server components get the searchParams as props by default!

    @JosephMaramba@JosephMaramba8 ай бұрын
  • This is so insightful and useful

    @kumardeepam@kumardeepam8 ай бұрын
  • This is just amazing. Glad I discovered you - amazing teacher. #subscribed

    @OpenCoreX@OpenCoreX8 ай бұрын
  • Neat approach, you just gained another sub

    @igboanugwocollins4452@igboanugwocollins44528 ай бұрын
  • So informative. Thanks for sharing

    @aamiramin6112@aamiramin61128 ай бұрын
  • freaking smart way of making the state in the URL never crossed my mind smart ass shit.

    @Alex-bc3xe@Alex-bc3xeАй бұрын
  • That is an excellent video! Thanks so much.

    @WojciechBlachut@WojciechBlachut8 ай бұрын
  • That was awsome, ty man!!

    @juanhedderich@juanhedderich8 ай бұрын
  • Amazing, super helpful!

    @loydcose2780@loydcose27808 ай бұрын
  • Sounds like bad UX to force the user to go back through query params in the history, since it’s not what the user expects, but I like the idea of using query strings for the other reasons. So I would just do it the way you did before you used , and turn it into its own reusable hook.

    @hojdog@hojdog8 ай бұрын
  • I'm doing a search function and was gonna use a state manager to manage this problem, perfect timing XD Thank you

    @MOURADSLIM@MOURADSLIM8 ай бұрын
  • 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?

    @alexkey9372@alexkey93727 ай бұрын
  • many thanks for great content ❤

    @user-qo6jf6jk2c@user-qo6jf6jk2c8 ай бұрын
  • Amazing, thanks mate 👌👌

    @mohammadmo9290@mohammadmo92908 ай бұрын
  • You got subscriber. Nice tutorial.

    @BK-qx3qf@BK-qx3qf8 ай бұрын
  • amazing content ! Keep up the good work sir

    @rubelhossain8517@rubelhossain85178 ай бұрын
    • Thanks, will do!

      @ByteGrad@ByteGrad8 ай бұрын
  • Just subscribed, I love your content man! I wish the audio can be improve soon.

    @geianmarkdenorte9874@geianmarkdenorte98748 ай бұрын
    • Yes, will improve soon. 2-3 more videos with this haha

      @ByteGrad@ByteGrad8 ай бұрын
  • Your videos are awesome! Just need to raise the audio volume a little bit.

    @AndersonSousa33@AndersonSousa338 ай бұрын
  • Huge fan of this approach :)

    @codewithguillaume@codewithguillaume8 ай бұрын
  • 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

    @nomadshiba@nomadshiba8 ай бұрын
  • We actually use this trick since 3 years in our React apps as well.

    @fulltimefrontend@fulltimefrontend7 ай бұрын
  • Always a super useful technique especially for UI's that you likely want to remember state when you copy and paste the link.

    @CuriousByte@CuriousByte7 ай бұрын
  • Very good video. Thank you.

    @ThugLifeModafocah@ThugLifeModafocah8 ай бұрын
  • 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).

    @runonce@runonce8 ай бұрын
  • Thanks for this video, it helped me a lot.

    @darwin2642@darwin26428 ай бұрын
  • You make absolutely great tutorials, thank you for sharing!

    @arinium@arinium2 ай бұрын
  • Never knew you have had a KZhead channel. I discovered you from your CSS udemy course. Quality work.

    @romeorel1679@romeorel16798 ай бұрын
  • Amazing feature for user experience and SEO

    @roby_codes@roby_codes8 ай бұрын
  • I cant thank you enough for this tutorial.

    @peteregbujie@peteregbujie7 ай бұрын
  • Exactly what I need right now.

    @johncaballero5463@johncaballero54638 ай бұрын
  • This was great & easy 👌🏻

    @shubhojeetbera@shubhojeetbera7 ай бұрын
  • 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

    @billypentester@billypentester8 ай бұрын
  • Hi, Which extension do you use for code block auto-suggestion? it's awesome!

    @ChiragGoyal777@ChiragGoyal7777 ай бұрын
  • I juste love your content. thank you for your useful videos

    @mohamedbelaouer1696@mohamedbelaouer16967 ай бұрын
  • Great video!! Thanks for sharing. 😉🔥

    @lukas.webdev@lukas.webdev8 ай бұрын
    • Thanks for watching!

      @ByteGrad@ByteGrad8 ай бұрын
  • I love your videos. Thank you!

    @thevasupodcast4561@thevasupodcast45618 ай бұрын
    • Glad you like them!

      @ByteGrad@ByteGrad8 ай бұрын
  • That's a really cool trick using the Link component to append a query param. Didn't know that was a thing!

    @ChrisHaupt@ChrisHaupt4 ай бұрын
  • I learned this when I was working with react router lifting state up to the url so even when user navigates around in app we can pass on this state so when they come back to same page the state doesn't get lost

    @prajwalchoudhary4824@prajwalchoudhary48248 ай бұрын
  • thank you, sir. from your knowledge. I am learned something new from this.

    @septiantonrezkirahmatulloh3837@septiantonrezkirahmatulloh38378 ай бұрын
  • Your tutorials are very informative

    @TitoMitto@TitoMitto7 ай бұрын
  • Thank you so much. Now I found a way to select filters without use client.

    @lorsothy6263@lorsothy62638 ай бұрын
  • 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!

    @bklynpeter@bklynpeter7 ай бұрын
  • Dzięki za porady!

    @dero433@dero4338 ай бұрын
    • Bez problemu!

      @ByteGrad@ByteGrad8 ай бұрын
  • I had similar use case today, pulled my hair for hours; Thanks brother 😊

    @raymondmichael4987@raymondmichael49878 ай бұрын
  • 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.

    @oidualx@oidualx7 ай бұрын
  • really. incredible. keep up

    @ammaralshathry9186@ammaralshathry91868 ай бұрын
  • 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

    @glauberbispo8922@glauberbispo89228 ай бұрын
  • watching your first video , became a fan of you broooooooo.. god bless you

    @mohammadshariarparvez669@mohammadshariarparvez6696 ай бұрын
  • It’s true, search params are indeed well applicable at storing a state.

    @edvinas396@edvinas3967 ай бұрын
  • Great approach

    @marchugans@marchugans8 ай бұрын
    • I agree, underused by many devs

      @ByteGrad@ByteGrad8 ай бұрын
  • Thanks for this content broth

    @iBryanKops@iBryanKops8 ай бұрын
  • Great tutorial! you got a subscriber

    @mohammedelmoutaouakkil@mohammedelmoutaouakkil7 ай бұрын
  • thanks, mate. it was great explanation :)

    @mmaarafat@mmaarafat6 ай бұрын
  • 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.

    @DiogoLScarmagnani@DiogoLScarmagnani6 ай бұрын
  • Thank you! Great content! Would you please also make a video on how to use addtocart in nextjs without Redux/context api?

    @mohdsahil226@mohdsahil2268 ай бұрын
  • What kind of state is best stored in the URL? Should simple data, like the e-commerce example you showed or pagination information, always be stored in the URL because of the simplicity and ease of storing/sharing?

    @jaysonacosta6945@jaysonacosta69458 ай бұрын
  • thank you very much for this Great explanations,,!,,!!

    @HerrThomasE@HerrThomasE8 ай бұрын
  • Hello ! Thanks for your video, I am currently on a projet with a stack with Adonis & Inertia, does it works with ServerSideRendering?

    @axellambert5795@axellambert57957 ай бұрын
KZhead