I'm wondering if I should use properties (not props, not state) in React component?
For example,
var myComponent = React.createClass ({
_text: '', // Something like this, a property other than props or state
});
What are the pros and cons, and what are the use cases?
Properties are great for storing data that isn't related to the view, but useful for modifying behaviour.
Why not state
or props
? state
should ideally be modified when calling setState
. But calling setState
also calls render
, leading to performance overheads. Although, we can cancel the render
call by overriding componentShouldUpdate
, but that's making things too complicated. So, state
is not the best place. props
seems like a good candidate, but, it can be over-written beyond our control, so that's not ideal either.
An example use case: you have a resource allocated in componentDidMount
, that needs to be cleaned up. The best place to do that would be in componentWillUnmount
. But how would you keep tabs of which resource was allocated? You use properties.
React.createClass({
componentDidMount() {
// `allocateResource` is entirely made up, but functions like it exist.
this.someResourcePointer = allocateResource();
},
componentWillUnmount() {
// `deallocateResource` is also entirely made up.
deallocateResource(this.someResourcePointer);
},
render() {
return <div>{/* ... */}</div>;
}
});
Some real-world examples:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With