2

I have this code in my React component.

What I need is to reuse some components and function from other files.

But some functions update my state.

I wanna know what is the best practice to accomplish this.

MyComponent primary:

import React, { Component, Fragment } from "react";

import { GenericFunction, GenericComponent } from "./functions.js";

class MyComponent extends Component {
  state = {
    myValueState: false
  };

  render() {
    const { myValueState } = this.state;

    return (
      <div>
        <GenericComponent
          GenericFunction={GenericFunction}
       // GenericFunction={GenericFunction.bind(this)} // -----> With this it works good, but is this a best practice?
        />
      </div>
    );
  }
}

export default MyComponent;

functions.js file:

export function GenericFunction(items) {
  if (items) {
    this.setState({ ...this.state, myValueState: true });
  } else {
    this.setState({ ...this.state, myValueState: false });
  }
}

GenericFunction={GenericFunction.bind(this)} is this a good way?

I have heard about problem with bind(this). Am I wrong?

1 Answers1

3

If your purpose is to only bind the function then you can do it in constructor only one time like this

class MyComponent extends Component {
  constructor(){
    super();
    // bind the function only once
    this.GenericFunction = GenericFunction.bind(this)
  }
  state = {
    myValueState: false
  };

  render() {
    const { myValueState } = this.state;

    return (
      <div>
        <GenericComponent
          GenericFunction={this.GenericFunction} // And use it like this
        />
      </div>
    );
  }
}
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
  • 1
    And it is the same of this: `GenericFunction={GenericFunction.bind(this)}`? Are there benefits using `constructor()`? –  Jan 17 '18 at 17:45
  • 2
    @JohnSam Yes. In lifecycle of a component, `render` function may be called mutiple times. So if you `bind` the function inside `render` then it will create a new function everytime the component is rerendered, resulting in more memory consumption. – Prakash Sharma Jan 17 '18 at 17:49
  • 2
    @JohnSam, its better to do it in constructor because render method is called multiple times and each time `.bind(this)` will create a new function if you write it in the render method. You might look at this question which addressed this issue, https://stackoverflow.com/questions/45053622/how-to-avoid-binding-inside-render-method/45053753#45053753 – Shubham Khatri Jan 17 '18 at 17:50