Reputation: 276
I am currently implementing a drag and drop system, in one of my js file I have implemented a functional component using React hooks, I have been working with class components, and I am not very familiar with the functional component of React.
So I know in class component, this.setState
will re-render, however, when I use setState in functional component it does not re-render the component.
Here is my code
// My state declaration
const [items, setItems] = React.useState({
row1: [],
row2: [],
row3: []
});
...
// This is my setItems call
setItems(prevState => {
let tempHolder = items;
// itemArray is a value passed down as props
tempHold.row1 = itemArray;
return tempObj;
});
I know that the problem causing this to happen is that React thinks my return value is the same as items
, so it did not cause setItems
to re-render, but I am not sure how to fix this issue.
Upvotes: 0
Views: 515
Reputation: 371168
You need to make sure the expression you return from the setter function is not ===
to the expression currently in state:
const [items, setItems] = React.useState({
row1: [],
row2: [],
row3: []
});
// ...
setItems({
...items,
row1: itemArray
});
(since the setter function is named setItems
, that's the function name you should call - not setVideos
)
Whether in class components or in functional components, don't mutate state - create new objects instead.
In this case, you might also consider having separate state variables, eg:
const [row1, setRow1] = useState([]);
and then you just have to call setRow1
without messing with any of the other rows.
If you have lots of rows, I think an array of arrays in state would make more sense:
const [items, setItems] = useState(() => Array.from({ length: 5 }, () => []));
// ...
setItems(items.map(
(item, i) => i === 0 ? itemArray : item
));
Upvotes: 1