amit kumar
Welcome to my Social Blog
2y ago

There is one prop in React which is often used. Still, we don’t know how it works internally. The magical props we are talking about is the key prop.

The key prop is used by React to identify which items have changed, are added, or are removed. It is used commonly when you use elements inside an array.

Controlling react component instances

This is another little known secret about React key prop. The key prop in React allows you to control a component instance easily in just a single piece of code. It allows you to return the exact same component, but force React to unmount the previous instance of that component, and mount a new one.

Unmounting the previous instance simply means that all state that had existed in the component is completely removed and the component is reinitialized.

The above component is a very simple React component which increments the count every time you click on the button.

The above code adds a reset button near the counter button. When you click on the counter button, it’s count is incremented. When the reset button is pressed, it will reset the count to zero.

One important thing to notice here is that the App component is not sending any value to the counter. It is just changing the key every time a button is pressed.

That single piece of code is doing the reset magic. Whenever the key of a component is changed, the new instance is created. The new instance will always have a new set of states. This is why the reset button works and the counter gets to zero when reset is clicked.

A closer look inside the component

Below is the console log displayed when app is loaded:

Below is the console log displayed when counter value changes:

Below is the console log displayed when counter is reset:

If you look closely, you will notice that when the counter is reset i.e. its key is changed. The entire component is recreated. The state is reinitialized and the component is remounted.

This pattern is useful when you need to reset an entire component on a specific event or change. Use this pattern wisely, as changing keys initializes the component which can also result in performance issues when used in data heavy applications.

What will you write today?

Write, publish, get feedback, and become a better writer.

Trusted by 75,000+ writers