Recently in my job, I was working on a project. I have to build a component that searches particular product from the json based on SKU code and fill all the details.
Here is the function.
searchProduct = (value, index) => {
const matchedProduct = this.state.products[value];
if (matchedProduct && matchedProduct.name) {
const billProducts = this.state.billProducts;
billProducts[index].desc = matchedProduct.name;
billProducts[index].rate = String(matchedProduct.price);
billProducts[index].sku = matchedProduct.sku;
billProducts[index].hsn = matchedProduct.hsn;
billProducts[index].gst = matchedProduct.gst;
billProducts[index].cess = matchedProduct.cess;
const qtyInput = document.getElementById(`qty-${index}/2`);
qtyInput.focus();
}
};
Now at first glance, It was looking perfect and also working as expected. But when I was reviewing my code, I find that I am not setting the state after updating it. I was shocked, How the hell all functionality is working.
I dig deeper in react and Js theory. After researching a bit I found some amazing facts.
Lets look at them one by one
1. Arrays and Objects are passed by reference in JS
This is the root cause of this unexpected behaviour.
const billProducts = this.state.billProducts;
Although in this line it looks like I am creating another Array billProducts, but since this.state.billProducts
is array, it is just a reference. I am directly mutating the state. So even if I am not setting the state, all changes are visible in component.
2. How does React work with this?
React works with virtual DOM, in background it checks if the previous state and current state is same or not. If it differs then, It re renders the component. But in this case it is not re rendering, because I am directly mutating the original Array, reference is same and I am not calling this.setState
, hence React does not re render.
Although It seems good, because we are saving the renders. But it might result in unexpected behavior. Since React does not re renders, other state might not change which might affect the UI.
React is build on the concept of Immutability. You should not mutate the state directly. Use setter function to always change the state.
In my case, It doesn't cause any issue, but still I used this.setState()
.
I never knew about this concept in JS and React. So thought of worth sharing with my network.
Top comments (0)