I am trying to set the state using React hook setState() using the props the component receive. I\'ve tried using the below code:
import React,{useState , us
For that, you need to use the useEffect
so your code looks like.
As you want to avoid to re-render again if pros didn't change then you have to check first on useEffect and then set the props to current variable.
import React, { useState, useEffect } from "react";
const Persons = props => {
// console.log(props.name);
const [nameState, setNameState] = useState(props);
console.log(nameState.name);
console.log(props.name);
useEffect(
() => {
if (nameState !== props.name) {
setNameState(props.name);
}
},
[nameState]
);
return (
My name is {props.name} and my age is {props.age}
My profession is {props.profession}
);
};
export default Persons;
Demo