Home > Mobile >  React Redux passing props componentDidMount to useEffect
React Redux passing props componentDidMount to useEffect

Time:09-03

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');
        }
       
   }, )
}

CodePudding user response:

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])

   ... 
}

  • Related