Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use properties (other than props or state) in React?

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?

like image 508
YiFeng Avatar asked Sep 06 '15 14:09

YiFeng


1 Answers

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:

  • subscribing to and unsubscribing from event emitters
  • having a pool of canvas contexts, if you need to spawn multiple canvas contexts
like image 82
Sal Rahman Avatar answered Nov 15 '22 11:11

Sal Rahman