Constructed instances in React state

Viewed 644

I don't like a ton of logic in my classes. Sometimes, I want to pull out something and make a new type (like what used to be standard coding). If I have some utils/Dev.js like

function Dev(x) {
  this.x = x
}
Dev.prototype.inc = function() {
  this.x = this.x+1
}

If I were to instantiate a React Component with this in the constructor

this.state.dev = new Dev(42)

this.state.dev is not gonna have any access to this, so it can't inc. Did I miss something or are constructed instances useless here?

1 Answers

The Dev instance can absolutely call its inc() function. I included a snippet below to show this.

I wouldn't say constructed instances are useless it just depends how and why you use them.

The reason it might not be a good idea is because if your intention is for the component to update on changes to the instance's state (in your case, the x variable), then it won't happen because the Dev instance in the state was not directly changed via setState().

function Dev(x) {
  this.x = x
}
Dev.prototype.inc = function() {
  this.x = this.x+1
}
Dev.prototype.get = function() {
  return this.x
}

// Example class component
class Container extends React.Component {

  constructor(props: IAppProps) {
        super(props);
        
        this.state = {dev: new Dev(42)};
    }

  handleInc() {
    this.state.dev.inc();
    this.forceUpdate();
  }

  render() {
    return (
      <div>
        <h1>{this.state.dev.get()}</h1>
        <button onClick={() => { this.handleInc(); }}>Increment</button>
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Container/>,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Related