Very simple code here. I'm wondering if this is the expected outcome. I'm upgrading an npm
module and it requires I pass these items to useState
which was not previously necessary. Unfortunately, I guess this can't be done with useState
? Am I right? I'd love to be wrong.
Where props.items
contains an array of class-based React components, useState
returns an empty array:
const [items, set] = useState(props.items);
Input:
Output:
*Note, images use prop spreading inside of array because I'm out of ideas besides, rework all the things.
Very simple code here. I'm wondering if this is the expected outcome. I'm upgrading an npm
module and it requires I pass these items to useState
which was not previously necessary. Unfortunately, I guess this can't be done with useState
? Am I right? I'd love to be wrong.
Where props.items
contains an array of class-based React components, useState
returns an empty array:
const [items, set] = useState(props.items);
Input:
Output:
*Note, images use prop spreading inside of array because I'm out of ideas besides, rework all the things.
Share Improve this question asked Feb 6, 2020 at 19:39 SlboxSlbox 13.1k16 gold badges64 silver badges131 bronze badges2 Answers
Reset to default 12This is not really recommanded you better do it in the useEffect
because Props
in Initial State is an anti-pattern.
const [items, setItems] = useState([]);
useEffect(() => {
setItems(props.items);
},[props.items]);
You should have no issues with using react element array as the input to useState. But, whenever you initialize your state with props coming from parent, you also need to re-update your state once the prop from parent changes. Otherwise it will point to the old state passed down from parent in the first pass. And the way to do that is to do a setItems with useEffect hook
useEffect(() => {
setItems(props.items)
}, [props.items])
btw this will only check for the reference equality between the old and the new array, if you want to do deep comparison, you should probably be using something like use-deep-compare-effect