How to access the previous props in React Js

Last updated : Jul 30, 2023 12:00 AM

Comparing the previous props with the current props is helpful to avoid unnecessary component re-renders. This article explains how to access previous props in both functional and class components.

Here is an example of where previous props are helpful in a class component.

componentDidUpdate(prevProps: Props, prevState: State) {
   if(prevProps.color === "green" && this.props.color === "blue"){
      console.log("Show Loading!!!")
   }
}

React Js class components have a built-in solution to access the previous props. Here is how I can compare the previous props to current props in the componentDidUpdate() lifecycle method.

componentDidUpdate(prevProps: Props, prevState: State) {
   if(prevProps.color === "green" && this.props.color === "blue"){
      console.log("Show Loading!!!")
   }
}

The complete example is listed below.

import { Component } from "react";

interface Props {
   color: string
}

interface State {
   color: string
}

export default class ChildComponent extends Component<Props, State>{

   componentDidUpdate(prevProps: Props, prevState: State) {
      if(prevProps.color === "green" && this.props.color === "blue"){
         console.log("Show Loading!!!")
      }
   }
   render(){
      return <div style={{backgroundColor: this.props.color}}>Color</div>
  }
}

Previous props in functional components

Unlike class components, functional components do not provide an out-of-the-box solution to access the previous props in lifecycle hooks. Therefore, I must implement a solution to preserve the previous props. Below is one way to do it.

const usePrevious = (color: string) => {
   const prev = useRef<string>()
   useEffect(() => {
      prev.current = color
   }, [color])
   return prev.current
}

The useRef() returns the same reference each time the component re-renders. Therefore, prev.current preserves and returns the previous value and updates to the new value.

import { useEffect, useRef } from "react"

interface Props {
   color: string
}

export const FunctionalComponent = (props: Props) =>{
  
   const prevColor = usePrevious(props.color)

   useEffect(() => {
      if(prevColor === "green" && props.color === "blue"){
      console.log("Show Loading!!!")
      }
   })

  return <div style={{backgroundColor: props.color}}>Color</div>
}

const usePrevious = (color: string) => {
   const prev = useRef<string>()
   useEffect(() => {
      prev.current = color
   }, [color])
   return prev.current
}
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...