02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Working with the React state

Working with the React State: A Foundation for Understanding Redux

Before diving into Redux, it's crucial to understand the React state and its limitations. In this lecture, we revisit how to work with state in React, providing a foundation for understanding why and when it's beneficial to shift towards a more advanced state management solution like Redux. This recap aims to solidify your knowledge of managing local component state in React and set the stage for introducing more sophisticated state solutions in subsequent lessons.

What is React State?

React state is a built-in feature that allows components to manage and react to dynamic data. It is one of the core concepts of React that helps components keep track of changing information. State is particularly important when dealing with data that changes over time, such as user inputs, fetched data, or the results of user interactions with the UI.

In this lecture, we enhance our Counter component by introducing state to keep track of the count. By using state, the counter value can dynamically update when users click on the + or - buttons.

Setting Up State in React

To create a React component with state, we need to use the constructor method to initialize state. The constructor is a special method that gets called when an instance of the class is created. The state is defined as an object, and each key-value pair in this object represents a piece of data that the component will manage.

Here's how the Counter component is updated to include state:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
  }

  render() {
    return (
      <div>
        <h2>{this.state.counter}</h2>
        <button onClick={this.stepUp}>+</button>
        <button onClick={this.stepDown}>-</button>
      </div>
    );
  }
}

export default Counter;

Breaking Down the Key Elements

  1. Constructor and State Initialization: The constructor is where the initial state is defined. In this example, the state has a single property, counter, with an initial value of 0.

  2. Accessing State in the Render Method: The value of the counter is accessed in the render() method using this.state.counter. By wrapping this.state.counter in curly braces ({}), we insert the dynamic value directly into the JSX to be displayed in the browser.

  3. Event Handlers for State Changes: We define two methods, stepUp and stepDown, to handle incrementing and decrementing the counter value. The onClick event handler is added to the buttons, allowing them to modify the state when clicked.

Updating State in React

React provides a method called setState() for updating the state. This method ensures that the component re-renders whenever the state changes, allowing the UI to stay in sync with the data. Below is an example of how to update the state in the stepUp and stepDown methods:

stepUp = () => {
  this.setState({ counter: this.state.counter + 1 });
}

stepDown = () => {
  this.setState({ counter: this.state.counter - 1 });
}

Handling Scope Issues in Event Handlers

When using event handlers in React, developers often encounter issues with the this keyword, particularly with class components. In JavaScript, the value of this can change based on the context in which a function is called. To ensure that this refers to the component instance, we use .bind() or arrow functions.

In the constructor, we bind the stepUp and stepDown methods like so:

this.stepUp = this.stepUp.bind(this);
this.stepDown = this.stepDown.bind(this);

Alternatively, we can define these methods as arrow functions, which automatically bind this to the component:

stepUp = () => {
  this.setState({ counter: this.state.counter + 1 });
}

Limitations of React State

While the React state is a powerful tool, it has limitations, especially when building larger applications where multiple components need to share or access the same data. In such cases, passing state down through props can become cumbersome, leading to issues like prop drilling, where data has to be passed through multiple levels of components that do not directly need it.

In this lecture, we highlight the challenges of relying solely on local component state:

  • Scalability: As your application grows, managing state locally within each component becomes complex. It becomes increasingly difficult to keep track of the flow of data.
  • Data Consistency: When multiple components need access to the same piece of state, managing that data in a consistent manner becomes challenging.
  • Prop Drilling: Passing state down through multiple levels of components leads to tightly coupled components, making the code harder to manage and maintain.

These limitations are what drive us to look for better state management solutions, such as Redux, which we'll introduce in the next section.

Preparing for Redux

The goal of understanding the React state is to set the stage for exploring how Redux can alleviate many of the limitations we encounter with local component state. Redux provides a predictable, centralized way to manage state across your entire application, making it easier to manage and debug complex data flows.

In the upcoming lectures, we'll discuss how to integrate Redux, creating a more scalable and maintainable state management solution for our applications.

Conclusion

In this lecture, we covered the fundamentals of working with React state and how to set up and modify state within a component. We explored using event handlers, managing scope, and the limitations of local state management. Understanding these limitations will help you appreciate the advantages of more sophisticated state management tools like Redux.

Stay tuned for the next lecture, where we will dive into Redux and learn how to use it to manage state in a more organized and efficient way. This will help take your React applications to the next level, enabling you to build more complex and scalable projects.

Happy coding!

Video Transcript

00:00In the last lecture, we created our React component,
00:03our first one in this lecture.
00:06We're going to continue down this path
00:07as we add a state into our react.
00:10And we're gonna, it's in many ways, it's a refresh,
00:13it's not a deep dive into it as we cover that
00:15and it's covered in many other titles on React itself.
00:18But we're gonna show you, uh, I'll show you a quick overview
00:20of how State works
00:21and React, thinking about also the limitations of state
00:25and really why would we want to leave state
00:28and try to figure out a better way to solve these stuff.
00:31And, and literally this is the, the core concept behind it
00:34where we're gonna understand why
00:35and when is it a good idea
00:37to start extracting your data out.
00:39With that said, let's jump into it
00:41and let's see, how do we use the React state?
00:44Alright, let's continue.
00:45So, uh, by the way, I couldn't find the React thing, that's
00:49what you were saying in the last lecture,
00:50but the reason was is
00:51because I had to actually close down my console
00:55and only then go back to the console
00:57and then it would be there as it was previously.
01:00Okay, so let's continue down our path
01:02and we really want to connect these plus and minuses
01:05and we're gonna start off
01:06by doing this internally inside of React.
01:09So you'll see basically
01:10where do things get complicated when we do this natively
01:13inside of React Beyond the philosophy
01:16that we will talk about really, really soon.
01:18But this is gonna be the last lecture
01:20that doesn't involve Redux.
01:22Okay? So let's go ahead inside of our counter itself,
01:24what I'm gonna do next is I want
01:26to actually trigger our buttons
01:28and I want to basically have your a real counter.
01:31To do that, I'm gonna have to do a couple of things
01:32and for one, I'm gonna start off
01:35by actually setting up a constructor to our component.
01:38So I'm gonna type your constructor.
01:42Cons, cons, constructor.
01:47Now our constructor, every time we create a constructor,
01:49we have to call super as the first thing we do
01:52and send our props value, which is gonna be the property
01:55that is being sent into our constructor.
01:58In it will be the, the properties that we send into React.
02:01Now we're not gonna talk about really about the
02:03theory of React at all.
02:04How does React work? That is something you're gonna find in
02:07one of my previous titles,
02:09but you just have to know that the constructor
02:11expects some properties.
02:12I'm sure you've worked with them already if you've been
02:14playing in React and you just have to set these two lines
02:17whenever you're setting up your constructor.
02:20Now I'm gonna go ahead and create my initial state.
02:23So I'm gonna create a new state object right inside
02:26of the constructor and send inside of it an object
02:29that I'm gonna set that object
02:30to have a property called Counter
02:33and it's gonna set its default value to be zero.
02:36Its initial value whenever the component is
02:38constructed to be zero.
02:41The next step inside of my render method itself,
02:43I'm gonna go ahead here and replace the actual code of zero
02:47to be our, this state
02:50dot counter literally printing out whatever is inside
02:54of this state into our JSX, starting with a curly bracket,
02:57closing with curly bracket.
03:00That's all I had to do to make sure
03:01that the value will be zero.
03:03And if I go back into my application
03:05and uh, take a peek, you'll see
03:07that we'll have your zero just as before.
03:09Beautiful. It's time for us
03:10to make these buttons actually do something.
03:13And to do that I'm gonna go ahead into my button itself
03:16and I'm gonna add an on click.
03:21And then on on on our on click, we're gonna call a method.
03:24Let's call the step up,
03:28we'll call the step up function method on click.
03:32When we're in a minus, we're gonna call this step down.
03:36So let's also make sure that we create those methods
03:39so we have your step up.
03:42Now I don't care about the uh, properties that might be sent
03:45with the button itself 'cause we just don't care about the
03:47job, the the HTML directly at all.
03:50And also for our step down,
03:52we're gonna create the same thing.
03:54Now all that's left for us to do is
03:56to actually change our state,
03:57but there's a few things we that we have to do.
03:59First of all, if I just do your console log for our this,
04:02you'll see that whenever I click on the button we are going
04:06to get the this, but it's not gonna be the this we expect
04:08the this is going to change
04:09because it's gonna be the this of the button itself
04:12because the button is gonna, the on click belongs
04:15to the button itself, but that's not what we want happening.
04:18So if I click here, you'll see
04:20that we're gonna get here null.
04:21We're not gonna get R this.
04:23It's basically getting confused,
04:24it's getting lost our scope itself.
04:27So what we wanna do is we wanna make sure
04:28that our on click here will actually keep its state.
04:32Now to do that, if we're using our methods here,
04:35what we're gonna have to do is go through the process
04:39of actually setting up
04:41and telling our component
04:43that anytime Step Up is called this dot Step Up Anytime.
04:47Step Up is called, we're gonna set it to be this step up
04:52bind to itself, making sure that it will stay bound.
04:56And if I go ahead and save this, but even
04:58before that, let me just go ahead
04:59and do thisSo for Step Down
05:05And I go ahead and save that.
05:06If I go back into my browser
05:08and I click you on the plus, you'll see
05:09that now we're getting our counter, which is exactly
05:12what we wanted to get.
05:14Beautiful. All that's left for us is
05:16to actually tie things in and call our this set state.
05:21We never will never actually update the state directly.
05:24We always call the set state
05:25because we don't want create confusion within
05:28the application itself.
05:29We never change that object directly.
05:32Instead of that, we're gonna go ahead
05:33and literally list out the things that we want to change.
05:36In this case, we want to take the counter
05:38and change it to be this, that state counter plus one.
05:44And for step down we want do it to the other direction.
05:48So for Step Down, we want to take the counter
05:50and subtract one out of it.
05:52And there we go. We've created our component
05:54and if I go back and I click on the plus, you'll see
05:57that my numbers will go up.
05:58If I click minus, my numbers will go down. Beautiful.
06:01Which is exactly what we wanted to happen.
06:04Now I just wanna talk a little bit further
06:06about the structures here.
06:08And by the way, notice how we're, we're,
06:10we have here these on clicks.
06:12I'm just gonna go ahead and copy this
06:14and I'm just gonna go ahead and copy that.
06:17And I'm just gonna also hide this one and comment it out.
06:21So I'm just gonna wrap it up
06:23and comment it out so that way it's uh, gonna be ignored.
06:26'cause I wanna show you how could you do this
06:28in one other way?
06:29Another way you could set things up is literally
06:31by sending an arrow function in this case.
06:35And what's nice about Arrow functions is
06:37that arrow functions keep their scope.
06:39So this is an e es six arrow function.
06:41It's a shortcut for creating functions.
06:44And literally I could go right inside of here
06:47and call whatever I want inside of this arrow function.
06:49If it's hard for me to see, I could even break a few lines
06:52to make it more, uh, visible for me.
06:55But I wanna make sure that I close that twice
06:58and I could go ahead and call my this set state.
07:02Now obviously this is incredibly dirty, incredibly ugly for
07:05for my perspective and that's why I'm not doing it this way.
07:08End of the day, you want your code to be legible.
07:10This is very un legible.
07:12But with that said, this arrow function, what will it do?
07:15It will actually make sure that
07:17whenever this is being called
07:18that this itself will stay the same within here.
07:21And thus if we go
07:22and try to click our button down,
07:24even though our button down now is inside of there,
07:27it should continue working.
07:28So you could go in both methods, both ways if you choose to.
07:32It's really just a question of preference.
07:34I personally would prefer to go
07:35through adding a little bit more code,
07:37but making my code a lot easier for me to read.
07:40'cause down the line readability is incredibly critical.
07:43But, so in this case I'm gonna revert back
07:45to the our original, but I'm gonna go ahead
07:48and make sure that you have here just in case you
07:51want to be able to see that.
07:52I'm just gonna go ahead here
07:54and leave all of this inside of A-A-A-A-A comment.
07:57So you could actually peek at this if you choose to do
07:59so at a later date.
08:01And that is it about how do we create STA
08:04and how do we set up React to work within its state.
08:10In this lecture we saw how to create the React state.
08:13And in the following, we'll continue down to see now
08:16that we have our internal data, how do we work
08:18with the reducers to set up a reducer that will act
08:21as our external data source.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!