LifeCycle Methods Replicated with Hooks

LifeCycle Methods Replicated with Hooks

The React tutorial will give some explanation of what each lifecycle method is for, and show how you can replicate similar behaviors using the Hooks API. React’s Hook API has been ever more popular and usable in the front-end world. Go from the class-based component architecture and implement same functionality with much faster and cleaner Hooks API!

For new developers coming from an Object Oriented Programming (OOP) background, classes and lifecycle methods may be much easier to understand. However, React’s Hook API has been ever more popular and usable in the front-end world.

What are Lifecycle Methods?

Here is a chart listing all the lifecycle methods in each phase of the component: mounting, updating, and un-mounting. As you can see, mounting and updating share couple of methods, but the others are very distinct to each step in the lifecycle.

Image for post

LifeCycle in Hooks

The rest of the article will give some explanation of what each lifecycle method is for, and show how you can replicate similar behaviors using the Hooks API.

Constructor

The constructor is a special one for React Components. The fact that React.Componentis a class, we have to extend this class from React for all our components. React hooks work a bit differently: they are not classes, rather functions. Meaning, we do not need a constructor!

However, the point remains: constructor is usually used for setting the initial state of your class based component. You can still set the initial state using the useState Hook:

// useState takes initial state as first argument
const [list, setList] = useState([]);

Or, you can also opt to pass useState a function, which will return your initial state. This can be useful for initial values that depend on some large CPU-intensive computations:

import {getInitialTodoList} from ‘./../data-api’;

// useState can take functions which return your initial state
const [list, setList] = useState(() => getInitialTodoList());

componentDidMount

This method is self-explanatory, it runs once when the component is first mounted. It is important to remember that it runs after the render method is completed and the DOM is drawn. If you call an API in this lifecycle method, make sure that you have your loaders set up, otherwise the data will be empty on first-draw.

You can accomplish the same using the useEffect hook. It takes in two arguments: the function to run, and the dependencies to watch. For this use case, we do not want to run this piece of code twice, so we do not have any dependencies.

useEffect(() => {

  // code to run after first render
  const subscription = myTodoObservable.subscribe(() => { … })
}, []) // Empty array means only run this code once after render

componentWillUnmount

The next one you might be wondering is about componentWillUnmount. In this method, you must unsubscribe to any event handlers. The nice thing about Hooks API is the fact that your code is so close together, and it uses closures to refer to variables.

useEffect can return a “clean up” function which will run once the effect is done, as so:

useEffect(() => {
  const subscription = myTodoObservable.subscribe(() => { … })

  // Clean up for “componentWillUnmount”
  return () => {
    subscription.unsubscribe()
  }
}, [])

render

The render method is the most used method, and it’s job is to: render the provided JSX. Since hooks are used in function-based components, we can return our own JSX just like render method. Simply remove the “render” keyword, and return the JSX.

function TodoList() {
  const [list, setList] = useState([]);

  return (
    <ul>
      {list.map(item =>
        <li key={item.id}>{item.name}</li>}
    <ul/>
  )
}

componentDidUpdate

This one gets a bit tricky, because it is called every single time that the props or the state updates (coming from a parent component or global contexts). componentDidUpdate takes in 3 arguments:

  • prevProps: props from the last render
  • prevState: state from the previous render
  • snapshot: the value from getSnapshotBeforeUpdate which we will talk about next.

The reason you would run this method is because something in your component’s state or props has updated and you need to react to it (pun intended). You can accomplish this same thing by running an “effect” when your prop or state value updates.

Let’s say that you need to call an API whenever your list of todo items reaches a multiple of 5. Usually, you might have some if-else block in componentDidUpdate. Let’s do that using hooks:

function TodoList() {
  const [list, setList] = useState([]);

  // effect to run
  useEffect(() => {
    if (list.length % 5 === 0) {
      // call your API here
    }
  // Our dependency is “list”. Run every time list updates
  }, [list]);

  return (
    <ul>{list.map(item => <li key={item.id}>{item.name}</li>}<ul/>
  )
}

Remember: you can have an indefinite amount of useEffect blocks which have the same or different dependencies. They will run in order from top-to-bottom. Try not to cram all your code into a single useEffect.

typescript javascript react react-hook developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Make an App with React JS / JavaScript: React and TypeScript

Building a Web Application as a Front-End Developer using React JS and TypeScript! Learn how to use the “Thinking in React” method and apply it to your real web application. We will be using real live weather data to display in our application and make our components reusable and maintainable.

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...

Hire Dedicated React Native Developer in India | React Native Development

Hire dedicated React Native developers for your next project. As the top react native development company we offer you the best service as per your business needs.

How to Build Meme Generator with React, React Hooks and TypeScript

The best way to learn something is by doing. It works even better if it means working on something for fun. So, how about learning about React, React hooks and TypeScript by building your own meme generator? This tutorial will show you how to do it.