Hacker News new | ask | show | jobs
by chatmasta 3312 days ago
Is it considered best practice to use the "key" of a child element to signify if it should rerender? This is what I've been doing and it seems to work well. If a parent updates its state, and then as a result, changes the props of some or all of its children, the parent sets the "key" of a child to effectively a hash of the props of that child.
3 comments

I believe it's best practice to set the key to be something that is based on the identity of the component to be rendered.

The idea is that this is used to suggest whether when rendering a component, the children are new components, or simply existing components with updated props.

E.g. You have a component that renders a list of items. If you add an item, what you would rather do is create a single new child component and re-use the previously generated children vs. discarding the child components from a the previous render and creating a brand new set.

If you create a key based on a hash of the props this will decrease the time taken to re-render an set of child components with identical props, but at the cost of discarding an existing component and creating a new one if one of the props changes.

Or something like that.....

See for a bit more detail: https://facebook.github.io/react/docs/reconciliation.html

I don't know the internal details but that sort of abuse of the key attribute seems like a dangerous thing to rely on.

I'll assume your key is quick to calculate. If a prop change causes the hash / key to change then react doesn't know how to reuse the dom fragment. I guess it will just reuse the stuff that's in the same location in that case so maybe it's fine. You'll lose the advantage that keys give you in the first case which is dealing with reordering.

And actually, just because the key changes or not, that doesn't cause a rerender or not. The rerender is always going to happen. Right? Unless I'm missing something.

keep in mind that changing the key will completely destroy and create a new element- a more expensive operation if all that's necessary is changing the class or something
nit: new component instance (not element)
I think we're both right- I believe it will create a new element and a new DOM element, rather than mutating the existing ones.
You're right. I misinterpreted your first comment to refer be referring to React elements, which is quite different from DOM elements https://facebook.github.io/react/blog/2015/12/18/react-compo...