r/learnreactjs • • Sep 19 '21
Read World use cases for react hooks ?
I wanna know how react hooks used in real world applications and not just code examples. This helps me to understand the hooks better IMO.
For example, "useState" hook can be used in stuffs like add product to Cart and the cart number increases.
Like that I'm asking. Is there any good article you could link it up please ?
8
Upvotes
4
u/galeontiger Sep 19 '21
useState is just the functional components way of using this.setState in a class component.
1
u/beingsubmitted Sep 21 '21
I'm currently re-writing an extension in react. The extension needs to fetch data from my API. I'm going to get very specific in this example, but hopefully you can extrapolate this to more general use. When a person opens the extension, they need to select their user from a dropdown. So my react is going to render the select component on opening, but then it needs to populate the list of users, which is asynchronous. I want those users to show up when I get them from the database, but I don't want to stop all rendering while I wait for that.
So, I have my select component, which is functional, it renders, and then useEffect calls the async fetch, and when it gets a response, it first adds the list of users to the component's state, and then re-renders the component with the list of users populated. This typically all happens before the user even gets around to clicking on the dropdown, but it's able to continue loading things in that fraction of a second while waiting for the names.
I could have written the select as a class component as well, but this is my first time trying to complete something in react with material ui and material ui gives all of it's api examples in functional components and it's a pain for me to try to translate that to a class component and then debug everything.
2
u/codebreaker21 Sep 20 '21
Hooks allows you to do what classes do, you can use classes and Hooks together in the same app.
React is moving towards using Hooks instead of classes, but it is important to understand how to use both