In this article, we will learn how we can implement states in React and implement the lifecycle methods in React. These lifecycle methods are used to control the components at different stages from initialization till unmounting.
Phases in lifecycle of Components
- Mounting(Component is added to the DOM)
- Updating(Component is updated in the DOM)
- Unmounting(Component is removed from the DOM)
Some of the basic lifecycle methods in React include render(), constructor, componentDidMount(), shouldComponentUpdate() etc.
Note: Since the version 16.3 of React some lifecycle methods like componentWillMount, componentWillReceiveProps, componentDidUpdate have been deprecated and are no longer in use. To use them we have to write UNSAFE_ before calling the method.
Let us see an example where we will implement state and lifecycle methods in React.
Open your react project directory and edit the Index.js file from the src folder.
First, we will create a timer without implementing state and lifecycle methods then we will see another example where we will update the state
Javascript
import React from 'react' ; import ReactDOM from 'react-dom' ; function showTime() { const myElement = ( <div> <h1>Welcome to neveropen!</h1> <h2>{ new Date().toLocaleTimeString()}</h2> </div> ); ReactDOM.render( myElement, document.getElementById( "root" ) ); } setInterval(showTime, 1000) |
Now what is the component in the above example? Actually, if you pay attention there is no component whatsoever. We are assigning a nested JSX element named “myElement” to contain the latest time and render the same every second, which is one of the worst ways to implement using React.
Creating clock by implementing state and lifecycle
Approach:
We define the class to be “Clock” we must think of the process first. Our clock has exactly two parts one is the title this should be implemented using props as it will not be changing throughout the lifetime; the other part is the time itself that should be changed at each second. It is clear that we have to set an interval to update the state at each second and this should be done as soon as the clock component is mounted. Thus, we have to use a lifecycle function componentDidMount() where we will set an interval to update the state, and to make the app efficient we will use componentWillUnmount() method to clear the interval. Let us see the following implementation.
Open your react project directory and edit the Index.js file from src folder:
Example:
javascript
import React from 'react' ; import ReactDOM from 'react-dom/client' ; class Clock extends React.Component { constructor(props) { super (props); this .state = { time: new Date() }; } // As soon as the Clock is mounted. // Start the interval "timer". // Call tick() every second. componentDidMount() { this .timer = setInterval( () => this .tick(), 1000); } // Before unmounting the Clock, // Clear the interval "Timer" // This step is a memory efficient step. componentWillUnmount() { clearInterval( this .timer); } // This function updates the state, // invokes re-render at each second. tick() { this .setState({ time: new Date() }); } render() { return ( <div> <h1>Welcome to { this .props.title} !</h1> <h2>{ this .state.time.toLocaleTimeString()}</h2> </div> ); } } const root = ReactDOM.createRoot(document.getElementById( 'root' )); root.render( <React.StrictMode> <Clock title= "neveropen" /> </React.StrictMode> ); |
Output:
Congratulations! You just created a React web app using States, Props, and some lifecycle methods. You might be asking is that all? No, it isn’t even a nibble of the whole platter stay tuned for the upcoming articles where we dive deeper into React and create some more projects on the go.