Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid constant re-render from "input" or "textarea" in react js

Tags:

reactjs

Currently in react js, when I want to bind a text area or an input with a "state", I will need to set the onChange method and setState() everytime user type in a single letter

I heard if you setState react js refresh and re-render everything in this component

Is there any more efficient way to do so? using "shouldComponentUpdate" will be improper in this case since if I don't make "state" update, all user input will be stuck..

like image 833
user3718395 Avatar asked Oct 25 '17 21:10

user3718395


1 Answers

Well, that's how you implement controlled input elements in React.

However, if performance is a major concern of yours, you could either isolate your input element in a separate stateful component, hence only triggering a re-render on itself and not on your entire app.

So something like:

class App extends Component {    
  render() {
    return (
      <div>
        ...
        <MyInput />
        ...
      </div>
    );
  }
}


class MyInput extends Component {
  constructor() {
    super();
    this.state = {value: ""};
  }

  update = (e) => {
    this.setState({value: e.target.value});
  }

  render() {
    return (
      <input onChange={this.update} value={this.state.value} />
    );
  }
}

Alternatively, you could just use an uncontrolled input element. For example:

class App extends Component {    
  render() {
    return (
      <div>
        ...
        <input defaultValue="" />
        ...
      </div>
    );
  }
}

Though, note that controlled inputs are generally recommended.

like image 167
Chris Avatar answered Oct 08 '22 17:10

Chris