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
The props
value in useState(props)
is used only during the initial render, further state updates are done with the setter setNameState
.
In addition, there is no need for useEffect
when updating derived state:
const Person = props => {
const [nameState, setNameState] = useState(props.name);
// update derived state conditionally without useEffect
if (props.name !== nameState) setNameState(props.name);
// ... other render code
};
From React docs:
[...] you can update the state right during rendering. React will re-run the component with updated state immediately after exiting the first render so it wouldn’t be expensive.
[...] an update during rendering is exactly what getDerivedStateFromProps has always been like conceptually.
In essence, we can optimize performance by getting rid of an additional browser repaint phase, as useEffect
always runs after the render is committed to the screen.
This is a contrived example illustrating above pattern - in real code you would read props.name
directly. See the React blog post for more appropriate derived state use cases.
const Person = props => {
const [nameState, setNameState] = React.useState(props.name);
// Here, we update derived state without useEffect
if (props.name !== nameState) setNameState(props.name);
return (
Person
{nameState} (from derived state)
{props.name} (from props)
Note: Derived state is synchronized/contains same value as props.name
);
};
const App = () => {
const [personName, setPersonName] = React.useState("Lui");
const changeName = () => setPersonName(personName === "Lukas" ? "Lui" : "Lukas");
return (
);
};
ReactDOM.render( , document.getElementById("root"));