-1

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?? I had just started learning react and know nothing about any other hooks, so Is there any way I can control the useState() hook, such that I can stop it from re-rendering it every time the input field is changed??

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'??

2 Answers2

1

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>
    )
};
Ali Shabani
  • 428
  • 2
  • 10
-2

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.

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32