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

react prevent child component from rendering
shouldcomponentupdate
react prevent re-render on state change
usestate prevent 're render
react hooks prevent 're render
usecontext re-render
shouldcomponentupdate hooks
react prevent page refresh

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..

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.

Avoid Unnecessary Rendering for Function Components in React , shallowly checks the props and rerenders if it detects new ones. Building a large scale React app may include some re-renders headaches. The growth of your app may cause you to spend a lot of time investigating why “heavy” components re-rendered much more

As @Chris stated, you should create another component to optimize the rerendering to only the specified component.

However, there are usecases where you need to update the parent component or dispatch an action with the value entered in your input to one of your reducers.

For example I created a SearchInput component which updates itself for every character entered in the input but only call the onChange function only if there are 3 characters at least.

Note: The clearTimeout is useful in order to call the onChange function only when the user has stopped typing for at least 200ms.

import React from 'react';

class SearchInput extends React.Component {
  constructor(props) {
    super(props);
    this.tabTimeoutId = [];
    this.state = {
      value: this.props.value,
    };

    this.onChangeSearch = this.onChangeSearch.bind(this);
  }

  componentWillUpdate() {
    // If the timoutId exists, it means a timeout is being launch
    if (this.tabTimeoutId.length > 1) {
      clearTimeout(this.tabTimeoutId[this.tabTimeoutId.length - 2]);
    }
  }

  onChangeSearch(event) {
    const { value } = event.target;

    this.setState({
      value,
    });

    const timeoutId = setTimeout(() => {
      value.length >= this.props.minSearchLength ? this.props.onChange(value) : this.props.resetSearch();
      this.tabTimeoutId = [];
    }, this.props.searchDelay);

    this.tabTimeoutId.push(timeoutId);
  }

  render() {
    const {
      onChange,
      minSearchLength,
      searchDelay,
      ...otherProps,
    } = this.props;

    return <input
      {...otherProps}
      value={this.state.value}
      onChange={event => this.onChangeSearch(event)}
    />
  }
}

SearchInput.propTypes = {
  minSearchLength: React.PropTypes.number,
  searchDelay: React.PropTypes.number,
};
SearchInput.defaultProps = {
  minSearchLength: 3,
  searchDelay: 200,
};

export default SearchInput;

Hope it helps.

How to prevent a rerender in React, Usually React components and their child components rerender if state or props change. However, by using React's API, you can step in and  It's a common occurrence to have components in the line of fire where they are forced to re-render despite not having any relevant prop or state changes. Our MenuButton example is just one such occurrence. The solution is to call shouldComponentUpdate and check whether any prop or state changes have taken place. To avoid you having to make this check all the time, there is a special kind of component that handles this checking automatically for you.

You need to bind the onChange() event function inside constructor like as code snippets :

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

  onChange= (e)=>{
    const formthis = this;
    let {name, value} = e.target;

    formthis.setState({
      [name]: value
    });
  }

  render() {
    return (
      <div>
        <form>
            <input type="text" name="name" onChange={this.onChange}  />
            <input type="text" name="email" onChange={this.onChange}  />
            <input type="text" name="phone" onChange={this.onChange}  />
            <input type="submit" name="submit" value="Submit"  />
        </form>
      </div>
    );
  }
}

Will a stateless component re-render if its props have not changed , avoid constant re-render from “input” or “textarea” in react js - reactjs. Every time you click on the button, the Foo function is called, but the DOM that it represents is not re-rendered. Because of that, there's no DOM update for that component at all. This is commonly referred to as an "unnecessary re-render."

You don't need a complicated react solution to this problem, just a little common sense about when to update state. The best way to achieve this is to encapsulate your setState call within a timeout.

class Element extends React.Component {
    onChange = (e) => {
        clearTimeout(this.setStateTimeout)
        this.setStateTimeout = setTimeout(()=> {
            this.setState({inputValue: e.target.value})
        }, 500)
    }
}

This will only set state on your react element a 500ms after the last keystroke and will prevent hammering the element with rerenders as your user is typing.

How does React decide to re-render a component?, No matter if you're here to get out of a render trap or if you simply want to learn new things, here's 5 tips that will hopefully save you a couple of  This component has two Props max_centers and centerId so anytime max_centers or centerId will change component will re-render. Let’s look at the props of FictionalComponent w.r.t time

avoid constant re-render from “input” or “textarea” in react js, There is no need to ask the child components to re-render for something that doesn't affect them. Ensuring your app is performant requires constant vigilance. This will define a new function reference for props.clicked on each re-render of the parent function. This will cause the props for Person to be changed on each render, causing Person to also re-render. Since you're not currently using id in personSelectedHandler, you could just omit the argument and keep the function reference constant:

5 Ways to Stop Wasting Renders in React/Redux, a HOC (higher order component) that allows us to wrap around a functional component and memoize it. React.memo() allows us to avoid multiple re-renders. Assuming you already know about basic techniques to avoid reconciliation, otherwise, you can read about it in an official react guide. There’re lots of common techniques , like using PureComponent, reselect and memoization, however when it comes to a complex application, even following all the rules still opens the gap for performance problems.

Avoiding Unnecessary Renders in React, This allows React to avoid potentially expensive DOM manipulation operations in Suppose we need to prevent a component from being re-rendered, we The render function creates a new book constant that means a new  But you won't want to re-render everything in the list, just the things that have changed. To help Vue keep track of what has changed and what hasn't, we supply a key attribute. Using the index of an array is not helpful here , since the index is not tied to specific objects in our list.

Comments
  • I wonder if there is a way to overload update so that you can track .val().length and only re-render/change state when the difference between the current length and the previous length exceeds a certain number. (I'm not a react person, just a basic js person, but react is relevant to my interests).
  • @cowbert, no this isn't really possible. If react is responsible for controlling the input, updating the state on every X letter typed would never work because you would never be able to type the first letter in to begin with. Simple demo: jsfiddle.net/1m0zrna8
  • setTimeout and clearTimeout are the most important parts of this answer. The rest is unnecessary complication.
  • This will just add 500ms delay until the typed text actually shows up in the input field. It can indeed avoid constant re-rendering, but the perceived performance is severely affected, and the experience will be broken.
  • @CookieMonster I disagree - you're not incurring any cost (other than creating a timeout) every call. You're also not blocking the text from showing up in the input field, because the input isn't bound to anything. Care to explain your reasoning?
  • Oh, I think I see the point you're trying to make now, but it's wrong. Maybe my example is insufficiently clear. The change handler isn't bound to the react element, it's bound to the input. The input will update immediately - because you don't bind val={this.state.val} on the input. Instead you just manually update the state on change. (But you do it with a 500ms delay.)