You might know that key
is a reserved prop in the React ecosystem.
I also guess you've get acquainted to key
while learning how to render a list, that you have to give a unique key to a list of items - maybe you don't even know why, you just do it.
Well, by understanding how this rendering thing works and why a unique key
is so important, you'll learn a new and very powerful way of using this key
prop, not even while rendering a list !
Why the key
prop must be unique in a list
React always try to optimise the rendering of components, by re-rendering only what changed between the previous state and the new. To do so, key
is one of the thing that tells react to recreate the element if the key
changed.
If you render a list and you don't setup the key
prop yourself, React will automatically set the key
to be the index
of the item in the array. That's fine if this array is static and never changes, but if it does change, it's gonna be a problem : your item will never re-render, because its props didn't change, neither its state.
What you should remember:
- When a component's state or props changes, React re-render it
- When a component's key changes, React re-create, with initial state and props
- When none of those change, React keep the component as is, no re-render is happening.
That's why if the items of your list change, you need to set each of them a unique key
, so that when the key
changes, the component recreates itself and your list updates
How to take advantage of the key
prop outside a list
Sometimes, a component needs to get its state reset to initial values. How to ?
-> have a sort of reset
function that reset all states: that can be tedious, and sometimes mistaking
-> change the key
prop of this component
I'm a big fan of the second option that I use a lot around my project : it's only a few lines of code maximum, it's 100% efficient, no mistake possible.
One of my colleague told me a few days ago: "That little hack is nice, but is it a proper way to do ?"
Well, this hack is not my own creation, I've learned it from another dev, but I never checked if there were official guidelines for it, and guess what : now with the new React docs, it has !
https://beta.reactjs.org/apis/usestate#resetting-state-with-a-key, by Dan Abramov himself.
Have fun !
Top comments (0)