I'm asking if there is (and if yes, what is) the recommended way to initialize state variables in React hooks with a value from the props
.
So I assume I have a component like this:
function SomeComponent(props) {
return (
....
);
}
I can use useState
to create a variable for this component, like this:
const [someVariable, setSomeVariable] = useState('someValue');
So far so good. My question is now, if I want to initialize the variable with a value from props, is it recommended to to it directly like this:
function SomeComponent(props) {
const [someVariable, setSomeVariable] = useState(props.someValue);
}
or is it better to initialize it with null
and then use useEffect()
to set the value on load:
function SomeComponent(props) {
const [someVariable, setSomeVariable] = useState(null);
useEffect(() => {
setSomeVariable(props.someValue);
},[])
}
Maybe there are more ways, too. I was just wondering if there is a recommendation here or if in the end it doesn't matter which way you use.