Prevent form rerendering in conrolled react inputs

Viewed 337

I am new to React.js and recently I learned about controlled inputs in React.

Code:

Here's a sample implementation that I made:

import React, { useState } from 'react';

const MyForm = () => {

    console.log('rendered');  // Line 5
    const [text1, setText1] = useState('');
    const [text2, setText2] = useState('');

    const onSubmit = (evt) => {
        evt.preventDefault();
        console.log(text1, text2);
    }

    return (<form onSubmit={onSubmit}>
        <input type="text" value={text1} onChange={ev => setText1(ev.target.value)} />
        <input type="text" value={text2} onChange={ev => setText2(ev.target.value)} />
        <input type="submit"/>
    </form>);
};

Problem:

Performance.

Above implementation works correctly, but I noticed that every time one of the field changes, console.log('rendered'); at line 5 is called again, and the entire form seems to be re-rendered. I guess that this could cause some problem especially for more advanced forms with many input fields and heavy pre-processing, etc. Ideally only the field that has changed should be re-rendered.

So I was wondering if my understanding of controlled inputs and form is okay. If not what is more scalable way of implementing this?

1 Answers

Since the state changes, the component will re-render. this is normal. if you dont want that, you need to "export" your input fields to new components with their own state, but then you have to somehow ref these components back to your parent form component in order to get their current values when you are going to submit the form.

Check this link on how to use ref, but I think that the form should be way too heavy in order for you to consider such a senario of creating for each input its own state in order to avoid parent component re-rendering on every input change, or even change to uncontrolled component, which is not usually recommended.

Related