React setState working slowly when using in onChange

Viewed 486

I have a textarea which i'm trying to get value and set to state. but it's working so slowly so i'm typing some thing and i see value after 10-15 second. Why can happened?

my state:

constructor(props) {
    super(props);
    this.state = {
      comment: ''
    };
    this.getValue = this.getValue.bind(this)
  }

my onChange function:

getValue = (e) => {
   this.setState({comment: e.target.value})
}

my textarea:

 <textarea
   type="text"
   value={this.state.comment}
   onChange={this.getValue}
 />
4 Answers

The below snippet seems to work fine and without the delay that you speak of, is your code similar to this? Can you share some more details? Are state updates working correctly in the rest of the application?

class Thingy extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      comment: ''
    };
  }
  
  getValue = (e) => {
   this.setState({comment: e.target.value})
  }
  
  render() {
    return (
    <React.Fragment>
      <p>{this.state.comment}</p>
      <textarea
       type="text"
       value={this.state.comment}
       onChange={this.getValue}
      />
    </React.Fragment>
    );
  }
}

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

Have you tried using hooks?

import React, { useState } from 'react';

const App = () => {
  const [comment, setComment] = useState('');

  return (
    <div>
      <textarea
        type="text"
        value={comment}
        onChange={e => setComment(e.target.value)}
      />
    </div>
  );
}
export default App;

This works fine for me. See it in a fiddle: https://jsfiddle.net/wbkjenay/

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { comment: '' }
  }

  getValue = e => { this.setState({comment: e.target.value}) }

  render() {
    return (
    <div>
        <textarea
            type="text"
            value={this.state.comment}
            onChange={this.getValue}
        />
        <div>this.state.comment: {this.state.comment}</div>     
    </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

well this is hooks method hope it help!

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "name"
  const [name, setname] = useState();

  return (
    <div>
      <p>Your name :{name}</p>
      <textarea onChange={e => setname(e.target.value)} value={name}/>
    </div>
  );
}
export default Example

Related