1

How would I change componentDidMount(), componentWillReceiveProps(nextProps) to useEffect? I just cannot figure it out.

this one below is my code without using Hook. getting this.props.auth from reducers.

componentDidMount() {
  if (this.props.auth.isAuthenticated) {
     this.props.history.push('/main');
  }
}

componentWillReceiveProps(nextProps) {
        if (nextProps.auth.isAuthenticated) {
            this.props.history.push('/main');
        }
}

What I want to do here is to use Hook useEffect. I'm not figuring out how to pass this.props.auth.

import React, { useState,useEffect} from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

const LoginPage = () =>{
   const navigate = useNavigate(); 

   //componentDidMount()
   useEffect(() => {
       if (this.props.auth.isAuthenticated) {
            navigate('/main');
        }
       
   }, [])
   //componentWillReceiveProps(nextProps)
   useEffect((nextProps) => {
       if (this.props.auth.isAuthenticated) {
            navigate('/main');
        }
       
   }, )
}

sassy.M
  • 27
  • 6

1 Answers1

0

The react hook equivalent to the previous componentWillReceiveProps hook can be the useEffect hook, just specify the prop in the dependency array that you want to listen for changes.

From Official React Docs:

You can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

If you want useEffect to be called each time the auth prop changes, specify it in the dependency array in useEffect.

import React, { useState,useEffect} from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

const LoginPage = ({auth, ...rest}) =>{
   const navigate = useNavigate(); 
 
   useEffect(() => {
       if (auth.isAuthenticated) {
            navigate('/main');
        }
       
   }, [auth])

   ... 
}

Sanket Shah
  • 2,888
  • 1
  • 11
  • 22
  • 1
    thanks for the rapid reply. it totally makes sense your code. Just one quick question tho if you don't mind... the code works but I get a warning sayin "React Hook useEffect has a missing dependency: 'navigate'. Either include it or remove the dependency array " is this ok to leave it ? much appreciate your help. – sassy.M Sep 02 '22 at 14:04
  • It's OK if you leave `navigate` out of the dependent array. Checkout this answer: https://stackoverflow.com/a/55854902 – Sanket Shah Sep 02 '22 at 14:07