Slbox
Slbox

Reputation: 13108

Passing array of React components to useState returns empty array

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:

enter image description here

Output:

enter image description here

*Note, images use prop spreading inside of array because I'm out of ideas besides, rework all the things.

Upvotes: 10

Views: 30301

Answers (2)

Aziz.G
Aziz.G

Reputation: 3721

This 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]);

Upvotes: 12

Moinul Hossain
Moinul Hossain

Reputation: 2206

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

Upvotes: 2

Related Questions