I want to create a component Person that is fully controlled by its state. It should also be able to sync the props change (firstName, lastName) passed from its parent component to the state. I have the following code. It does what I want which is syncing props to state and re-render after state has been changed.
However one issue I noticed is that useEffect gets invoked after DOM update triggered by the parent props change. So the initial re-render is wasted since I only want it to re-render after useEffect gets invoked and state is changed.
import React,{useState, useEffect} from 'react';
const Person = ({firstName, lastName}) => {
const [name, setName] = useState(firstName + lastName)
useEffect(() => {
setName(firstName + lastName);
console.log("state changed!");
}, [firstName, lastName])
console.log("re-render!");
return <div>render {name}</div>;
}
export default Person;
I created a simple demo here https://codesandbox.io/s/sparkling-feather-t8n7m. If you click the re-render button, in the console you will see below output. The first re-render!
is triggered by props change which I want to avoid. Any idea how to achieve this? I know there are other solutions such as making it fully uncontrolled, but I'd like to know if there is any workaround to this solution
re-render!
state changed!
re-render!