تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Intro to React State0:00

React and JSX is already super cool just as a templating language to break your UI down in components like we've done up to this point. But the main reason you'd want to use something like React is how simple and predictable it makes building reactive interactive UIs. In this lesson you're going to have your first taste of React state and I'll do my best to make sure you understand exactly how it works.

of React state and I'll do my best to make sure you understand exactly how it works. Quick housekeeping update. We've got a new logo, Tara, this is Pixel the DevOps mascots, which is going to replace our chat GPT generated logo placeholder. Big shout out to Adrian for designing these super cute mascots. Oh, and speaking of deaf pups, look who I found. Hello. Alright, we'll start super simple with interactivity

Extract LikeToggle Component0:42

Oh, and speaking of deaf pups, look who I found. Hello. Alright, we'll start super simple with interactivity and we'll take a look at this like toggle here. This happens in the PuppysList component, specifically in the PuppyCard and all the way down here in the button. I don't wanna be scrolling up and down. I want us to hyperfocus on the state here. So what I'll do is create a separate component just for our likeToggle.

So what I'll do is create a separate component just for our likeToggle and we'll put it in its own file, so likeToggle.tsx and we'll export a function called likeToggle. Go away copilot. And in there we will return our button and back in the PuppiesList. Instead of the button here we will use the likeToggle, which should have been auto imported and yep, it has.

Instead of the button here we will use the like toggle, which should have been auto imported and yep, it has. Alright, so you can see we have an issue. We will having this puppyID placeholder logic here and for now I will just set this to true so it's always true. And so as a result I'm expecting all the puppy cards to have this liked status and yeah they do. Cool. And to make a component even more minimal, this long SVG is annoying me here.

Replace SVG With Icon1:43

Cool. And to make a component even more minimal, this long SVG is annoying me here. And so I'll replace it with an icon from the Lucid React library that I was talking about. I'll quickly install the library npm install lucid-react. And I may be pronouncing lucid force, but in my head this is a French word just like Veit, it's veit. And so I'm going to continue pronouncing it lucid until someone tells me that I'm wrong.

And so I'm going to continue pronouncing it Lucid until someone tells me that I'm wrong. Okay, so now check this out. Remember that in Lucid React, the icon we want is called hot. So before my SVG here, I will look for the hot component. There it is, I can auto import it and let's take a look. Hey, pretty nice looks like we are lucky that the default size for Lucid React icons is 24 by 24, which is exactly what we had set in our SVG.

that the default size for Lucid React icons is 24 by 24, which is exactly what we had set in our SVG. But the very cool thing about Lucid React components is they can take a class name. So I will copy what I've got here into the heart and if I take another look now our icons are identical perfect so I can get rid of the entire SVG and now we have a pretty nice minimal components that fits in the window. I'm pretty happy with that. Okay, so now we have to work out

that fits in the window. I'm pretty happy with that. Okay, so now we have to work out how to make this toggle work. For now it's always set to true, it's always liked, which is kind of nice. You should like all the puppies, but we wanna make sure that we can actually toggle on enough dislike status. So adjusted like status

Attempt Toggle With Variable2:59

on enough dislike status. So adjusted like status and I think we need to start by having a variable, let likedStatus and set this to false to begin with. And then down here we're going to replace our true with the value of likedStatus. Don't worry about the squiggle here, it's gonna tell me I should use const because it's not reassigned, but we will reassign it. Just gimme a second. So our likeStatus is false

because it's not reassigned, but we will reassign it. Just gimme a second. So our likeStatus is false so I expect every puppy to be unlike indeed. And so now we need to find a mechanism to change to toggle the likeStatus when we click on this heart. In other words, when we click on this button here on click, we want to change the value of the status. Hmm on click, let's try on and hey look at this. Looks like we have all sorts of button events and do we have onClick?

Looks like we have all sorts of button events and do we have onClick? We sure do. This show does sound similar to the native browser onClick event. So to learn more about this we're going to fire a function and let's call it handleClick. It doesn't exist yet, but up here before my return statement I will have a function handleClick which receives the event in question. And so let's just console.log the event.

click which receives the event in question. And so let's just console.log the event. So when I click on the button, it's going to fire the handleClick function, which is going to log the event passed to it. So let's try this. I'll open the dev tools and I'll click one of the buttons and looks like we have a synthetic base event. These events belong to React and basically reimplement the native browser DOM events.

These events belong to React and basically reimplement the native browser DOM events but try to streamline some cross browser inconsistencies so you can see all the event properties and matter of fact, there is a native event property inside of it which is the actual native event. Okay, so why don't we onClick, try to change the likeStatus value. So in the handleClick function we will go likeStatus equals the opposite of what it is.

So in the handleClick function we will go like status equals the opposite of what it is and we are not using the event here anymore. And let's see what happens. I'm going to click on the hard click, click, click, click, click, click, click, click. Nothing happens. Well that's a bummer, hang on, what's going on here? So let's try to console.log status. Alright, click true, click false,

So let's try to console.log likeStatus. Alright, click true, click false, true false, true false. Wait, what? The likeStatus is changing and we rely on that likeStatus to toggle the style of the hearts but it's not changing what's going on. And this brings a really important point to understand about how React updates the UI and it has to do with component re-renders. Instead of just updating variable values.

and it has to do with component re-renders. Instead of just updating variable values as they change, React is going to wait for some sort of signal that something has changed and then re-render the whole component with the new values after the change. So here we are defining a likeStatus local variable and we indeed change the value as we've seen in the console log, but React doesn't know about this change and

Use useState for Re-renders5:42

as we've seen in the console log, but React doesn't know about this change and therefore does nothing about it. This signal that React is waiting for in order to re-render a component can only be triggered with React internal state. And so instead of using a local variable here we are going to have to use React states. I'm going to have a const liked state and this could be called anything

I'm going to have a likeState and this could be called anything and I will like I mentioned, tap into React's useState mechanism that it provides and once again let's set the default state to false. So if I hover over this, you will see that the likeState is actually an array of two things. A Boolean value which is our true false and then a dispatch set state action which sounds like an event emitter or some sort of action dispatcher.

and then a react dispatch set state action which sounds like a event emitter or some sort of action dispatcher. In other words, this useState function gives you to think a state value and a state setter function. And for that reason it's quite common to destructure these two values and have something like isLiked, that could be our state value. And then setIsLiked, that could be our setter.

that could be our state value. And then setIsLiked, that could be our set. So isLiked is going to be a boolean value. And then the setIsLiked is this dispatch setState action? If this is confusing at first, don't worry, this is normal. Essentially you can think of the first value, the value here as the equivalent of that. But in React's internals, matter of fact this useState function is called a React hook because it lets us hook into React's internal way

of fact this used state function is called a React hook because it lets us hook into React's internal way of managing re-renders. So let me remove the comment and check this out. We are going to replace our liked status with the isLiked value in our button. Logic here so isLiked and remember it's set to false by default and so all the puppies should be not liked, but if this was set to true by default,

and so all the puppies should be not liked, but if this was set to true by default, now all of them are liked. So we're going to try now to use the React internal state setter function to toggle the status. So up here in our handleClick function, I will use the setIsLike function and set isLike to the opposite of what it is exactly like we've done here.

and set isLike to the opposite of what it is exactly like we've done here. But with React's internal state setter, let's set the default value back to false. And this time when I click on the heart, woo-hoo, it's working. We can now toggle the likes for each individual pup. Whenever we click the like toggle, we trigger React's internal state set function, we modify the internal state and

we trigger React's internal state set of function, we modify the internal state and therefore ring the alarm that signal that React listens to and so it sees the state change and then re renders the components. So you now understand that you cannot use a local variable because when you change its value, React won't hear about it and won't do anything about it. But even if it did, check this out, I'm still logging the likeStatus here.

But even if it did, check this out, I'm still logging the like status here every time we change it. And so it should go from false to true, back to false and so on. But look at what happens now. true, true, true, true, true, true, true. It's always true. Can you work out why this is happening? Well, every time we re-render the component because react states told it that it needed to re-render,

Well, every time we re-render the component because react states told it that it needed to re-render, we are going to rerun, dislike, toggle function. We are going to redefine dislikeStatus variable to false and then set it to true and log it and then the component re-renders, we reset it to false, re-change it and re-log it so it's always true, true, true and so on. These are the two magic superpowers of the react useState hook.

These are the two magic superpowers of the react useState hook. For one, it's able to trigger an alarm that something has changed and tell react to re-render a component, but also the state can persist through multiple re-renders whenever we re-render the component. The whole function reruns, as you've seen, the local variables get redefined but the state value persists through re-renders.

the local variables get redefined but the state value persists through rear-ends. Like I said, it can feel confusing at first but I promise you in no time it'll feel very natural. Matter of fact, let's do a second quick example that should feel a lot more comfortable for you. Let's say I want to add a clickCount increments next to the button. So every time I click it, the number next to it is going to increment by one.

So every time I click it, the number next to it is going to increment by one. The great thing about the useState hook is you can have as many useState calls as you want. So if we wanted the count value, we don't really want to tie in with the isLiked, we can have another useState hook. So count, let's call it count and setCount and copilot knows exactly what I want to show you. And we are going to define a state value.

and copilot knows exactly what I want to show you. And we are going to define a state value that has a default of 0. So our is is like was a boolean this time our account is a number since we've set the default value to 0 and I'll get rid of this local variable here and these two lines. And I'm pretty sure that at this point you know how we going to increment the count by 1 on button click yep, that's right.

to increment the count by one on button click yep, that's right. We are going to call the setCount function and set our count to count plus one. Next, let's update our UI a little bit. I will add a class of flex items center gap 1 just so it looks nice and after the heart I'll have a span here with the count value. So to recap, we have a count state value and a setCount state setter, we set the state here on click.

So to recap, we have a count state value and a setCount state setter, we set the state here on click and we display the count value in the UI. And just like that, each toggle has the count set to zero and as I click on it, it increments by one as you can see already starts to feel very natural and pretty cool and I promise you this scales really nicely too. Alright, that was a key lesson here you've learned about the basics of React's internal re-rendering mechanisms.

Batched Updates and Functional setState11:12

Alright, that was a key lesson here you've learned about the basics of React's internal re-rendering mechanisms and also React internal state with the useState hook. Before I let you go, let me show you a slightly more advanced nuance of the React useState hook. That might save you some head scratches. Alright, so in the handleClick function, I will duplicate and even triplicate the setCount function call so that we are hoping to increment the count by three every time we click the button.

that we are hoping to increment the counts by three every time we click the button. Alright, so let's test it out. It should go to plus three, but it only increments by one. This is not a bug, this is a feature in React. React is going to batch together multiple calls to state setter functions inside a commit. So here's what happens in the code here we set isLike to the opposite. So it goes from false to true.

like to the opposite. So it goes from false to true. We set the count to count plus 1, so 0 plus 1 1, then we recall set count to count plus 1, but we haven't committed anything at this point. So count technically is still 0. And then we set count one more time with count still being 0 plus 1. And so as a result we have is like to true and count to 1.

And so as a result we have ease like to true and count to one. Now there may be situations where you do not want this batching to happen and so there's an explicit way to tell React to not batch these things together. In a commit, instead of using the count value directly in the setCount, you can pass a callback function that receives the count and then sets count plus one. Typically, when you use that, it's often called prevCount.

that receives the count and then sets count plus one. Typically, when you use that, it's often called prevCount to specify that this is the previous count value and this will become the new value derived from the previous one. So let me duplicate these two and remove these two. And this time, because we are using callback functions for each of the three setCount calls. By the way, this is a great example of what's called hot module reloading provided by vi.

By the way, this is a great example of what's called hot module reloading provided by vi. I have changed the code and saved it, but it has maintained the states to where it was before. So now when I click on one of the hearts, I'm expecting it to go to six, six and 4, 7, 10, 13, and so on. Pretty cool stuff, huh? The useState hook is only one of React hooks that let you tap into React internals.

The use state hook is only one of React hooks that let you tap into React internals. They're super powerful but also come with a set of rules of how you should be using them. As a bit of homework for this lesson, go check out the Rules of Hooks page on the React documentation. It's going to walk you through the things you should and shouldn't do when it comes to React hooks. And it's really important that you understand these.

and shouldn't do when it comes to react hooks. And it's really important that you understand these. The good news is ESLint react hooks rules are very good at telling you when you're doing something wrong. For example, one of the rules is you cannot use a react hook outside a react component. And so if I had this useState outside of the like Toggle component, I will instantly be notified of what I'm doing wrong and what I should be doing instead. Alright, whew. Lots of big learning in this video.

of what I'm doing wrong and what I should be doing instead. Alright, whew. Lots of big learning in this video. This is a pivotal one in your react learning. So if you need to go and re-watch it and re-watch it one more time if needs be, and then I will see you in the next one.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟