How to use state in React, fundamentals!

How to use state in React, fundamentals!

Hello, world!

I personally just started out learning react and I want to share in a pretty much simple way what I understand about react states and how to use. I'm a newbie at react and like always I just want to share one or two things. So if you are here, you are probably trying to understand how to work with react states,

Well, Good news! You are not alone. when I started off with react I had this issue of getting how states work. And like I always say it. if I can get it, then anyone can. i will walk you through the concept of react states and trust me. it's easier than you think!

What is state?

State is a JavaScript object that stores a component’s dynamic data and determines the component’s behaviour. Because state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive.

When adding states it's generally done on to a class component or a functional component.

What then is a class and functional component?

What is a class component?

A class component is simply a more featured way to define a React component. It also acts like a function that receives props (params in react), but that function also considers a private internal state as additional input that controls the returned JSX(JavaScript XML). An interesting fact about a class component is that it requires you to extend from React.Component and create a render function which returns a React element.

React components has a built-in state object. The state object is where you store property values that belong to the component. When the state object changes, the component re-renders.

Example

Creating the state Object

The state object is initialized in our constructor:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {brand: "Ford"};
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

And our state object can contain as many properties as you like:

Specify all the properties your component need:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

Using the state Object

While trying to access the state properties in our component , we refer to the state object anywhere in the component by using this.state.propertyname syntax

Example

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
      </div>
    );
  }
}

Changing the state Object

To change a value in the state object, use the this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).

Example

For this we will defiantly need an onClick even handle for a button to update the state when the user clicks , Handling events with React elements is very similar to handling events on DOM elements. However, There are some syntax differences:

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string.

For example, the HTML:

<button onclick="activateLasers()">
  Activate Lasers
</button>

is slightly different in react:

<button onClick={activateLasers}>
  Activate Lasers
</button>

Continuing with our example, we will add a button with an onClick event that will change the color property:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

Note: Always use the setState() method to change the state object, it will ensure that the component knows it's been updated and calls the render() method (and all the other lifecycle methods).

What is a functional component?

On the other hand, a functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. It works slightly like the class component just here we don't have the this keyword that said we will get something like:

export default function Car() {
  const [state, setState] = React.useState({
    brand: "Ford",
    model: "Mustang",
    color: "red",
    year: 1964
  });

  const changeColor = () => {
    setState({ color: "blue" });
  };

  return (
    <div>
      <h1>My {state.brand}</h1>
      <p>
        It is a {state.color}
        {state.model}
        from {state.year}.
      </p>
      <button type="button" onClick={changeColor}>
        Change color
      </button>
    </div>
  );
}

We note that. we can set a state only with its setState method! From all evidence, it does sound less complex when we break it down and try to understand it in chunks!