Wheemangga

[React] Component Lifecycle Class Component

Mar 7th, 2023
733
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component } from "react";
  2.  
  3. class Lifecycle extends Component {
  4.   constructor(props) {
  5.     super(props);
  6.     this.state = {
  7.       count: 0,
  8.       isMounted: false,
  9.     };
  10.   }
  11.  
  12.   static getDerivedStateFromProps(props, state) {
  13.     console.log(" \nGet Parent State & Props", state);
  14.     return null;
  15.   }
  16.  
  17.   componentDidMount() {
  18.     console.log("\n %c MOUNTED \n", "background-color: cyan; font-size: 20px");
  19.     this.setState({ isMounted: true });
  20.   }
  21.  
  22.   shouldComponentUpdate(nextProps, nextState) {
  23.     console.log("Should update?", "Count :", nextState.count);
  24.     if (nextState.count > 5) {
  25.       console.log("UDAH GAK BISA UPDATE! COUNT UDAH ", nextState.count);
  26.       return false;
  27.     }
  28.     return true;
  29.   }
  30.  
  31.   // getSnapshotBeforeUpdate(prevProps, prevState) {
  32.   //   if (prevState.count !== this.state.count) {
  33.   //     console.log("Get Snapshot |", "Previous Count: ", prevState.count);
  34.   //   } else console.log("Snapshot kosongg");
  35.   //   return null;
  36.   // }
  37.  
  38.   componentDidUpdate(prevProps, prevState, snapshot) {
  39.     console.log(
  40.       "\n %c UPDATE \n",
  41.       "background-color: yellow; font-size: 15px",
  42.  
  43.       prevState,
  44.       snapshot,
  45.       " \n "
  46.     );
  47.     return null;
  48.   }
  49.  
  50.   componentWillUnmount() {
  51.     console.log("UNMOUNT");
  52.   }
  53.  
  54.   handleIncrementClick = () => {
  55.     this.setState((prevState) => ({ count: prevState.count + 1 }));
  56.   };
  57.  
  58.   render() {
  59.     console.log("\n %c RENDER \n", "background-color: green; font-size: 20px");
  60.     return (
  61.       <div>
  62.         <p>Count: {this.state.count}</p>
  63.         <button
  64.           className="border p-2 border-black rounded-md m-5"
  65.           onClick={this.handleIncrementClick}
  66.         >
  67.           Increment Count
  68.         </button>
  69.       </div>
  70.     );
  71.   }
  72. }
  73.  
  74. export default Lifecycle;
  75.  
Advertisement
Add Comment
Please, Sign In to add comment