Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active October 19, 2022 10:16
Show Gist options
  • Save ross-u/dade01d6a7e03f2aa064383d6515567a to your computer and use it in GitHub Desktop.
Save ross-u/dade01d6a7e03f2aa064383d6515567a to your computer and use it in GitHub Desktop.
React | Lifecycle Methods Exercise

React | Lifecycle methods - Exercise



Let's create a basic example so that you may visualise how React's Lifecycle Methods work in practice.


1. Create new react app

npx create-react-app react-lifecycles-example
cd react-lifecycles-example

code .

2. Create a src/components/ folder.


3. Create a component src/components/Counter.js and copy/paste the code snippet provided below.


Your src folder after creating the new component should look like this:

📦src
  📂components
   📜Counter.js
  📜App.css
  📜App.js
  📜App.test.js
  📜index.css
  📜index.js
  📜logo.svg
  📜serviceWorker.js

4. Update the src/App.js by replacing the inital code copy/pasting the code from the below App.js snippet.


5. Run the app in development mode.

npm start

Take a look at your Chorme Dev console, you should find the following result:

img


// App.js
import React, { Component } from 'react';
import './App.css';
import Counter from './components/Counter'
class App extends Component {
constructor(props) {
super(props);
this.state = { isRunning: true };
console.log('I am in the CONSTRUCTOR of the App.js.');
}
stopCounter = () => {
this.setState({ isRunning: false })
}
render() {
console.log('I am in RENDER of the App.js.');
return this.state.isRunning ? (
<div className="App">
<h2>Clicking this button will destroy the Counter component and clear the state.</h2>
<button onClick={this.stopCounter}>Stop the counter</button>
<Counter />
</div>
) : null
}
}
export default App;
// src/components/Counter.js
import React, { Component } from 'react'
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
console.log('I am in the CONSTRUCTOR of the Counter.js.');
}
counter = () =>{
this.setState({ count: this.state.count + 1 });
/* // Second way - using `setState` callback
(state) => {
return {
count: state.count + 1
};
}
*/
}
componentDidMount() {
this.timer = setInterval(this.counter, 1000);
console.log('Component DID MOUNT.');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component Counter UPDATED from: ', prevState.count);
}
componentWillUnmount() {
console.log("======== Component COUNTER is UNMOUNTED! ========");
clearInterval(this.timer); // !!!
}
render() {
console.log('I am in the RENDER of the Counter.');
return (
<h1> { this.state.count }</h1>
)
}
}
export default Counter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment