What Do These Three Dots `...` in React Do? spread operator
In React, you can use spread syntax to pass objects such as props without the need to pass individual values.
For example, these three components are equal:
function App1() {
return <Image width="50" height="100" source="img_source" />;
}
function App2() {
const props = { width: "50", height: "100" };
return (
<Image width={props.width} height={props.height} source="img_source" />
);
}
function App3() {
const props = { width: "50", height: "100" };
return <Image {...props} source="img_source" />;
}This syntax is particularly useful when you want to pass a dynamic object and do not know beforehand which properties might be present in it.
Another popular use case of spread syntax is to copy objects or arrays. Spread operator can create a new object or array with all of the properties or elements of the existing object or array.
For example:
const books = [
{ name: "War and Peace", read: true },
{ name: "Count of Monte Christo", read: true },
];
function addNewBook(newBook) {
return [...books, { ...newBook, read: false }];
}
const updatedBookList = addNewBook({ name: "Lord of the Rings" });In React, this comes in handy when you do not want to mutate specific data like state.