5 ms·
There you go. I thought `key` was something you just needed when creating child elements, so react knows which ones are which. I didn't realize it could be used
by quickthrower2 4y ago
There you go. I thought `key` was something you just needed when creating child elements, so react knows which ones are which. I didn't realize it could be used to create a new sandbox for state. But actually it makes sense! Because if you have a list of child items each with it's own state then React needs to manage that using the key. I never made this connection.
- dgb23 4y agoIt’s useful to think about key as the telling React of the identity of a component. Whenever you want a stateful component that can be identified by a unique name, you’ll likely want to tell that to React via key.
- sickcodebruh 4y agoMy concern with using `key` for this is that it’s somewhat of a booby trap for future consumers of the component. It requires some kind of documentation that you need to hope they’ll read. TypeScript won’t help you. It’s not common enough that they’ll think to go looking for it. It’ll break silently and they won’t know until there’s a problem. Is the best practice to wrap a keyed-to-reset-state component in an unkeyed component and then exporting that? Seems like an odd pattern.
- aeroaero 4y agoNot necessarily, the component itself can work without a key. Adding a key is just one approach to resetting component state from a parent. If a component can’t work properly without a key it should be wrapped further to make it usable rather than documenting it for all consumers.
- sickcodebruh 4y agoThat last bit seems like a recommendation that should be in the docs. It’s sensible from a “don’t leave boobytraps” perspective but it won’t be intuitive to many people. It’s one more little rule to learn, another comment on a sizable chunk of PRs. While it may be idiomatic and sensible JSX, it seems like an outlier for React, and I wonder if there’s an opportunity to improve the developer experience of this very common use case.
- quickthrower2 4y agoI think I agree. I commented a while back I prefer components that don’t reset state based on props anyway. Use state as little as possible and keep things pure and you probably won’t need this. Example: date picker only keeps the open/close ui state of the picker. The date is a prop and date change is an event. Instead of original date being a prop. Current date being local state.