Home > OS >  How do I prevent React from re-rendering a component with every change in input field?
How do I prevent React from re-rendering a component with every change in input field?

Time:12-17

So I have created a React components which has a input field and an onChange() which is used to update the value in useState() hook. For every letter I type into the input field the component is re-rendered. How can I prevent this??

const Def = () => {
    const [name, setName] = useState('');
    const [items, addItems] = useState([]);
    const addName = ()=>{
        addItems([...items, name]);
    }
    return(
        <div>
            <input type='text'
            value={name}
            onChange={e=>setName(e.target.value)} />
            <h2>{name}</h2>
            <button onClick={addName}>Add</button>
            {console.log(items)}
        </div>
    )
};

I have added the console.log to know the rendering activity and for every letter I enter into the input field the items are displayed on the console.

How can I stop the re-rendering of the component with every character change in the input field. Is there any way I can re-render the component only after clicking the 'button'??

CodePudding user response:

you can use ref to get the value of the input when button clicked

const Def = () => {
    const btnRef = useRef()
    const [items, addItems] = useState([]);
    const addName = ()=>{
        addItems([...items, btnRef.current.value]);
    }
    return(
        <div>
            <input type='text'
            ref={btnRef} />
            <h2>{name}</h2>
            <button onClick={addName}>Add</button>
            {console.log(items)}
        </div>
    )
};

CodePudding user response:

Why do you want to prevent rerender of this component? This is exactly how React is supposed to work. At every change in the input field, the component is rerendered in order to show the new contents of the input field.

CodePudding user response:

You can use the shouldComponentUpdate lifecycle method to control when a component re-renders. This method is called before a component re-renders, and you can use it to determine whether or not the component should actually be updated. If you return false from this method, the component will not be re-rendered.

Here's an example of how you can use shouldComponentUpdate:

import React, { useState } from 'react';

const Def = () => {
  const [name, setName] = useState('');
  const [items, addItems] = useState([]);
  const addName = () => {
    addItems([...items, name]);
  }

  // New method to control re-renders
  shouldComponentUpdate(nextProps, nextState) {
    // Only re-render the component if the 'items' state has changed
    return nextState.items !== items;
  }

  return (
    <div>
      <input type='text' value={name} onChange={e => setName(e.target.value)} />
      <h2>{name}</h2>
      <button onClick={addName}>Add</button>
      {console.log(items)}
    </div>
  );
};

Keep in mind that this will prevent the component from re-rendering with every change to the input field, but it will still re-render when the 'Add' button is clicked and the items state is updated.

Alternatively, you could use a controlled component pattern to prevent the component from re-rendering with every change to the input field. In this pattern, you store the value of the input field in state, and bind the value of the input field to the state using the value prop. This way, the input field is "controlled" by the component, and the component can decide when to update the value of the input field.

import React, { useState } from 'react';

const Def = () => {
  const [name, setName] = useState('');
  const [items, addItems] = useState([]);
  const addName = () => {
    addItems([...items, name]);
  }

  return (
    <div>
      <input
        type='text'
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <h2>{name}</h2>
      <button onClick={addName}>Add</button>
      {console.log(items)}
    </div>
  );
};

Using a controlled component will prevent the component from re-rendering with every change to the input field, since the value of the input field is being controlled by the component's state.

  • Related