I am trying to set initial state based on data from props.
const Calculate({data}) => {
const [number, setNumber] = data === 'end' ? useState(5) : useState(0);
return (...)
}
This gave me an error: React Hook "React.useState" is called conditionally. React Hooks must be called in the exact same order in every component render.
So I decided to update my code with useEffect:
const Calculate({data}) => {
const [number, setNumber] = useState(0);
useEffect(() => {
if (data === 'end') {
setNumber(5)
}
}, []);
}
However I'd rather not set the state initially to zero if I don't need to.
Alternatively can I solve it by making the initial value conditional?
const Calculate({data}) => {
const [number, setNumber] = useState(data === 'end' ? 5 : 0);
return (...)
}
Are there any side effects to this? Why would this work and not my original attempt?
const [number, setNumber] = useState(data == 'end' ? 5 : 0)