The Best React State Management Solution Has Been There All Along
Вставка
- Опубліковано 22 лип 2024
- We are all used to using the useState hook to manage state in React. We may even turn to more powerful state management libraries like Redux, but in reality the best state management for UX is most likely just the browser URL. In this video I will explain why that is and how you can easily swap to using the URL for state management.
📚 Materials/References:
React Router Tutorial: • Learn React Router v6 ...
Zod Tutorial: • Learn Zod In 30 Minutes
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Problem
00:45 - Solution With React Router
03:51 - What To Watch Out For
#ReactRouter #WDS #ReactJS
We've really come full circle. State belongs in the URL. That's the power of a website. This reminds me of the MVC days.
Depends on the case. For search parameters yes, it improves UX and the ability to share the page with your filters.
thats my response when i first saw SSR.. going back full circle to PHP
That never changed a part of the state always belonged to the URL, the issue is young people never learned it right in the first place, that's not a framework issue that's a learning issue.
All of this exists so that the top developers can earn fat stacks of money. And even those at the bottom can get some crumbs and scraps. It’s utterly pointless to be real, to the point of it being so ridiculous, that the whole point was missed by a mile from the start
Something something state us stored in the balls.....
But yeah we have come full circle.
But just to philospoize for a second, now we know why things were done in a certain way and its benefits
But more so i keep thinking , are all these techniques just the best it could have ever been given the state of how we use the web and internet,
Server actions, and now this, we're really going back and thinking we're inventing something new
For the sake of reactivity in UI , we are going to 90s era.
My thoughts exactly 10 seconds into video. "iF yoURe uSiNg StaTe uR doiNg iT WrOnGNG XD". cringe
As a web dev from the 90’s, it’s amusing seeing all these videos acting like they discovered something new.
100% agree.
@@ScytherDOTAits the goto for react "experts"
Just note, there are limits for the maximum allowed URL length in the address bar of browsers. This varies vastly between browsers.
Yes, for this reason it's often better to store this state on a backend and just return a short ID that you append to the URL.
@@risitas5874 Not sure if that's often better but at least that would be one way, yes.
@@risitas5874yep, I'm surprised this wasn't mentioned in the video.
@@risitas5874could you give a simple example of that please. Thank u
Or to use a state management tool for unauthorized users
Thanks for the video. Two days back I want through a detailed tutorial to build a simple Contacts from using the Remix framework; So watching this video I kind of revisited the concept of querystring (search params) approach of saving state.
We recently worked on this a lot of times in the project we are currently working, where we require to implement a filter for a set of records. The values are taken from a form and set to URL, and an useEffect was added for change in search params to call the necessary API. A lot of hassle was required to put the values from the URL back to the form when the page is refreshed.
Awesome video! I use this technique for all sorts of things, but never thought about the url replace optimization, that's clever. I have a hook (NextJS) that handles this for me, I'm just gonna add url replacement logic. Thanks, Kyle!
A small Feedback:- Your videos are indeed amazing but it would be better if you make videos keeping in mind about production level code and real world programming as this method in the video is only applicable to my "contact us" form. But generally all other forms I have worked on are not simple and doesn't only contain 2-3 text field. The point here I want to make is I like you explanation and that is why I need you to make some intermediate to advance videos about production and real world project programming. Keep going.
If he does it the tutorial video will be 10 hours long
@@isyedaliraza I mean like people who are working and have exp. of 2-3 years needs some brief but not very literal videos on real production level programming stuffs as they can watch 20-30 minutes of content each day.
He publishes those in the form of courses, and you gotta buy them. Quality comes at a price
@@someonewhowantedtobeahero3206 I know about it but I think you haven't seen the course catalogue or my feedback comment. The courses he sells are for beginners but not for intermediate to advance level.
@@MayankMishra-oy5xeSurely if you have 2-3 years experience you would know how to translate a concept shown in a simple example to something more complex.
Great but come on, this is how search pages were made 15-20 years ago during Vanilla PHP era. Query params in url. Sometimes I feel we (on the web) "rediscover" old ways of doing things and pretend we invented something revolutionary.
Yeah true. And often this is just completetely unneccessary too. React is already a mess without all these bells and whistles. And having the URL update in real time is just a no-no for me.
Same with the "new" server side rendering. Those thoughts are the problem of new developers (including me of course). We don't usually know how things worked before react, angular and vue. So we must be cautious with what we said and listen to the people with many years of experience.
That's why it's "Has Been There All Along".
Yup. It's like this startup idea someone had about Spotify, but selected playlists playing on "channels", and people were like "Congratulations. You've just invented radio".
I have been working in react for 5 years but I am using the URL from the start
it's not the first time when i working on something and Kyle gives me an advise i need. thanks for help
Converted my project over to this approach last night. It was the solution I didn't even know I needed. Thanks! I need to do some refactoring now as this approach results in some repetitive snippets of code since I have a few panels you can switch between and I want all search terms to be stored in the URL.
yeah I was looking for something like this for filtering.
I totally forgot about this hook! I recently faced similar dilemma with my custom data table component, but didn't have the time to look into it. I already use Zod and React Router, so it's going to be a piece of cake.
thank you for simplifying the web for me, now I can start building my dream project
Thanks! It is useful in Next.js server components when you need some state but don't want "use client"
Did you copy this from the other youtuber?
I thought the same, the other guy showed exactly the same but with a better UI.
Who's the other guy
I'm happy to see all the hype search params is getting!
I just recently implemented this on one of the projects. Quite useful!
Great Vid! Short and straight to the point
I love it when we keep going in circles
Thanks for your video, and make me think more about usage about it.
very nice, i'll def use this for my projects
Great topic to explore!
Great short video! Cheers!
Awesome explanation 🙏
youtube url has an encoded query param, how does it work? Is it handled in FE or BE to encode/decode it?
Nice, simple and clear sir
Loved the approach thank you:)
I've never seen the `prev.get("propertyname")` in JavaScript. is it a new method? or is it a custom one? or did I miss it?
i learnt a lot of these things by watching other sites like Jira work and learnt the hard way. I am thinking it is good to watch some tutorials as well. That replace: true was a new use case for me. Never took care of that.
great work bro. learned a new thing
How to implement with NextJS app router? putting router.replace in onChange makes slow...
This is actually very true. URL-driven applications are just how web was meant to be from the start and SPA fucked that up pretty bad.
Brilliant idea, use it on tax forms, credit card payments and login screens.
Can't wait 😍😍
As it was mentioned, it's for FILTERING DATA, not for AUTH.
@@spythere So, I can't use it on ANY FORM, only on FILTERS THE DATA?! That sucks.
Awesome video!
Thankyou, great explanation.
it's funny to write that because managing states with query parameters is the most oldest way to do it and until front-end frameworks everyone makes it with that way. This is a confession for how front-end frameworks sucks i guess.
Thanks, this is really a good idea 👍
what can i do to make a research on search box to redirect to resul page ?
cool, will use that in the current project ;)
Que buenos videos chabón!!!❤
Great concept!
Anyone know what the .get() method is. Isnt that from a map? Here it is with an object?
I knew about this hook before, but I hesitated to use it anyhow. Now as I see and understand, how this approach spices my page up. There is nothing left for me than to sit infront of my PC and to make some changes in my code.
Bytegrad yt channel uploaded a video on the same topic a few days ago yeah it's good to use the query parameter he shows some more cool techniques with Nextjs btw nice video
That's what i noticed too
i was thinking the same someone already a made video on this topic
this is not the first time he upload the same topic after Bytegrad LOL
Content leech
I wish I would have known how important it is to not have possibly diverging states between backend-react-html without the mistakes that made me come to this company is conclusion myself. Search params are a nice way to reduce state complexity.
how it's better that useState?
If you send HTML to the client then you don't have to worry about this problem at all.
does this rerender everything? or just related components?
can any one say what is the nextjs router equivalent for {replace: true} in setSearchParams?
Amazing video!
Videos like this are a good reminder why PHP never dies to this day. Maybe they got it right all along - use URL as state, use sessions not JWT, use MySQL for DBs (there's Strapi in the React world for that). 😂
Anyway, thanks Kyle for this video. I still think it's quite informative for those who've never been into PHP.
You seem to not understand the difference between JWT and session, first one can be used cross domain, the other cannot... Also all the state cannot and should not be stored in the URL, just what you need like filters. About the database choice, it always depend on what you need and what you can afford, it's not just "use X DB", also PostgreSQL is a more advanced DB and free like MySQL/MariaDB.
Oops, somebody doesn't know tongue in cheek when he sees it... 😛
@@Thassalocracy Apologies if your comment was ironic, it is not really obvious.
Can you please provide the git hub link for the same?
What keyboard and switches do you use?
Man, thanks for sharing!!
Thanks! Very nice!
Hi Kyle!
how we can add multiple search params in url like " products?category=shirts&color=red&size=lg "
You have to destructure the current search param object and then add attributes
daxx, although i'm a backend developer only, but i know this is soso useful
Why state should belong to the url? I could simply create a FilterProvider and it will work fine. Why url though?
Interesting, ByteGrad just put out a video on this a few days ago. coincidental timing, or a query prams just making a comeback right now? or another reason maybe 🤔
Everyone is a copycat and they're looking for views
@@ajfalo-fi3721 I don't want to make any assumptions and I am a big fan of WDS. and I will grant that query params are a useful tool, just strange to see it framed in this specific way Rrght after another up and coming web dev UA-camr has done the same.
I'd like to see how y'all approach this problem when you gotta load select dropdown with i18n, everytime I had to implement something like this, it looked ugly lol
Are you using a BrowserRouter? Surely there’s a lot more to it in prod as you can’t just refresh / paste in the url and get the router to take you back to the correct route? (404 scenario) Would you handle state on your server? Or use a HashRouter?
Good insight.. btw http should be stateless right?
holy shit. WHy is this something I learned only now
how to clear q= when input is empty?
It would be really great if you can teach us how to make our own rich text editor as a notion editor (example Editor.js).
Thank you, more trick about react router v6 woahh
Exactly the relevant stuff. This is premium content.
@@roodood I was building a SAAS aplication and you guessed it, using state to remember what filters applied. Making the url dirty wasnt attracted to me but it seems it was the preferred approach. It might be simple and basic but thats all thats needed. So knowledge thats relevant to work is premium.
some of the comments a bit crazy - remembering that not all of us started/even started learning pre react , I mostly now learned react - no idea about jquery and previous , i had made 1 purely html/js/css project for university but never done a project since in pure html/js/css. this to me sounds like an option but it seems that it has more specific use cases
Great thanks
any ideas how to do this in Svelte/SvelteKit?
This is a great feature. How would we go about hiding the information displayed in the URL for security purposes?
Just don't put sensitive information into the URL in the first place
Wow Homelander started teaching webdev
what’s the idea of this if you’re using a “state” like hook. it would be a client component on next too
Thanks
your thumbnail looks very similiar
What about the url limitations (how complex it can get)?!
The React world really is something different. Just wow.
With due respect are you sure this can be used as a replacement for state management libraries like redux, jotai, flux etc?
No
This is only for data filtering purposes, you can't use this elsewhere without compromising security
I’d love for you to do one of these but the state value be an array instead of a simple string. I’m struggling with how to use this process with more complex data
f
I'd only use the URL parameters for filtering purposes personally. I do not believe that state belongs in the URL to a much greater extent than that. There are a few neat things you can do here and there, but keeping all state in the URL is not a good approach.
Using an identifier is part of filtering, just as a side note, so ?id=abc123 would still valid in this regard. You could have the identifier as a part of the actual URL and not just a parameter, but that's nothing more than an implementation detail.
Do You sill use xstate?
are we going back to php now?
Nice Brother
Is there any way to hide this from URL? Any other methods for doing so?
You would need to use another technique to store that data, like *localStorage* or *indexedDB*.
You haven't mentioned that "set state" function of useSearchParams behaves differently from "set state" function of useState hook when it's called multiple times during the same render cycle
Amazing
Is there another way to persist states between pages?
redux , contextapi orrr prop drilling kinda
what happen if the user messes up the URL?
Nothing really... it would be able to change the checkbox state by the url and the input text value as well... nothing more
lol i implemented this in my codebase like 3 days ago with zustand, just had to add this replace prop for the same result
Brother kyle we need your help , please create video for react native and its complex navigations
Doesn't this introduce a potential XSS vulnerability?
The string value in the `q` parameter is directly bound to the ``s value attribute.
Not really, the value is assigned using JavaScript property assignment so there's no string escaping issue. In SSR the string will be escaped properly. If you ever wrote the URL to the page without proper escaping you might have an issue but that's not dependent on this technique.
React handles (escape) this automatically when rendering, you can try it yourself.
There is no two way binding in react :)
Great video + Awesome Solution! 😉🔥
next best thing to add is testing.. please show that more since it's like 80%of the job anyway
how do i do this in next tho
it's not working with nextJS :/
As usual, context is king; you can't judge this approach without it. CC# and password? Bad idea. Generic product search page? Pretty solid use case.
Of course, urls have like a 2k limit, can be caught in proxies/routers, require en/decoding, used for phishing attacks, etc. As usual, its all tradeoffs.
I think for most viewers of this channel, that first bit is obvious.
@@gosnooky you're overestimating the people that watch stuff like this.
Killer and short!
I just wish browsers handled this better. I often see hundreds of entries in my history, because I typed a couple of words. Of course you can debounce the query update, but it's far from perfect that way.
Atleast give credit to Bytegrad who literally made this exact video a week before you.
this is hook import from react or react-router-dom???
React-router-dom
@@ananthb2435 thx
We really are returning to monke.
I would add local state and debounce url update for higher responsiveness
Have you noticed some kind of slowness with URL updates? They seem pretty fast to me.
Awesome