DEV Community

Ahmad Jamaly Rabib
Ahmad Jamaly Rabib

Posted on

Learning React State and LifeCycle

Hello again! πŸ‘‹πŸ˜

Last time we created React Components both class and functional but these aren't fully functional yet. Today we will look at how React components work independently using State.

React state

From the Component section we found that Class Component is stateful. But we don't know what is state yet πŸ˜…. Let's find out about it. πŸ₯³πŸ’ͺ

So, let's first prepare our project to work with React State. Let's start with our Component files
react_component

Till now we haven't worked with data changes in React. React only changes two times.

  1. When the data/state changes.
  2. When there is change in the props from outside the Component.

We know that if we pass a parameter to the React component and we change the value of the parameter , in this case React changes.

This is called change by props. This can be controlled from outside of the Component. Like we did pass the locale props data to the Component from outside here.

function App() {
  return (
    <Clock locale="en-US"></Clock>
  )
}
Enter fullscreen mode Exit fullscreen mode

In React, State is a memory of a component. It is like a database of the Component.

React works with virtual DOM first to compare the previous state with current state. If there is any change then it paints it in the browser DOM.

But State change only happens inside the React component and the data change should happen by "React way".

So, what is a "React way" data change?

As we have extended the React.Component class we can use the methods of the Component class of React, like we are using the render method.

Let's create the constructor method for the Clock class.

constructor(props) {
  super(props);
  this.state = { date: new Date() }
}
Enter fullscreen mode Exit fullscreen mode

In the constructor function we will have the props as parameter. After that we are using super which calls the base class constructor method properties.

In this way we can use the Component class constructor method's all properties staying inside the Clock class.

Then we created the property this.state which is an object. In this state object we can define any types of properties.

Here, we have defined the date property inside the this.state object.

Now, we can use this.state.date instead of the new Date() inside the render method.

render() {
    return (
      <div>
        <h1 className="heading">
          <span>Hello <span>{this.props.children}</span> { this.state.date.toLocaleTimeString(this.props.locale) }</span>
        </h1>
      </div>
    );
  }
Enter fullscreen mode Exit fullscreen mode

By this way we prepared the methods so that it will update in case of any state change in the "React way".

We can also skip creating a constructor for class if we only need to initialize the state. We can use the public class field syntax to define the state.

state = {date: new Date()}
Enter fullscreen mode Exit fullscreen mode

We have to use the setState method to change the data using the React way. But to do that, we actually need to know when to change the state before changing the state. πŸ˜πŸ€”πŸ₯΄

This leads us to understanding the Component lifecycle. πŸ€— Let's go through some of the methods of React lifecycle.

1. componentDidMount

This method is called immediately after a component is mounted in the real DOM.

This method isn't mounted when the rendering is done in React virtual DOM, it actually mounted when everything is compared, calculated and then when the final result is painted in the browser DOM.

But if we implement this method we also need to find out and update other lifecycle methods to avoid bugs.

2. componentDidUpdate

If we define this method, React will call it immediately after the component is re-rendered with updated props or state. This method isn't called for initial render.

We use it to manipulate the DOM after the update.

3. componentWillUnmount

If we define this method. React called immediately before the component is destroyed.

It performs any necessary cleanup in this method, such as canceled network requests, or cleaning up any DOM elements created in componentDidMount.

Now let's update our Clock class using some React LifeCycle methods. Let's first add the componentDidMount method to make the clock functional. We will use the setInterval method to make the change per second by calling the setState method. Inside the setState we will pass the updated object.

componentDidMount() {
  setInterval(() => {
    this.setState({
      date: new Date()
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

So in this way we have made our clock to self update.
Image from Gyazo

But this timer is resource hungry right. And this will continue to run even if we go to another page or route.

So, to make it stop when we move to another route we will use another lifecycle method componentWillUnmount.

But let's first make a separate function tick for the this.setState.

tick() {
  this.setState({
    date: new Date()
  });
}
Enter fullscreen mode Exit fullscreen mode

And now let's replace the codes inside componentDidMount.

componentDidMount() {
  setInterval(() => this.tick());
}
Enter fullscreen mode Exit fullscreen mode

Now let's clear the timer. But to do this we will add another property this.clockTimer in which we will define the current date.

componentDidMount() {
  this.clockTimer = setInterval(() => this.tick());
}

componentWillUnmount() {
  clearInterval(this.clockTimer);
}
Enter fullscreen mode Exit fullscreen mode

Yes! We are done with the proper functional Clock component. Now we can use this Clock anywhere! πŸ™ŒπŸ™πŸ€—

I still have a lot of things to learn on State. I am still going through the React documentation for state.. Hope I will get a better understanding after going through it.

Here is the code for today's task.

Thank you for reading. If there is anything missing please comment. I will try to learn and update. Thank you! Bye! πŸ‘‹πŸ™

Top comments (0)