Improving performance of React component | using less state variables

Improving performance of React component | using less state variables

Great performance is never a luck, it takes a lot of focus, heart and hard work - someone said

React has evolved over the years and react components have really became powerful. We can use many hooks in functional components that really made react components powerful. In this blog we will be discussing about 2 approaches of improving rendering performance of react components.

Use state variables only when they are required.

Over time I have realized React developers creates the variable to save forms data and listen for onChange event on it.

For e.g.

import {  useState } from "react";
const Login= props => {

    const [username, setUsername] = useState('');

    const onChange = event => {
        setUsername(event.target.value);
    }

    return(<>
                 <input type="text" value={username} onChange={onChange} />
            </>)
}

Now if you observe for every letter we type in the component it's re-rendering. Let's add the useEffect in the component to measure the performance.

const Login = props => {

    const [username, setUsername] = useState('');
    const onChange = event => {
        setUsername(event.target.value);
    }

    useEffect( () => {
        console.count('rendered'); // count tell how many times logs are printed
    });

    return(<>
        <input type="text" value={username} onChange={onChange} />
    </>)
}

If you run above program you would see to type my username akash19 into username field it is re-rendered 7 times.

performance-1.png

Can we solve this problem?

Yes, if possible you can use refs instead of using state variables, it avoids the multiple re-renderings and you can read the data whenever you want.

const Login = props => {

    const usernameRef = useRef(null);
    useEffect( () => {
        console.count('rendered'); // count tell how many times logs are printed
    });

    return(<>
        <input type="text" ref={usernameRef} />
    </>)
}

Now, if you type your username into input field and check the performance. Your re-rendering would be improved signficantly.

Note: Any time you need username you can simply do usernameRef.current.value

Read more about useRef

performance-2.png

Don't jump directly to refs eveytime.

Though re-renderings are more in reacts way to controll the forms, it is recommened to use it. It makes a lot of things easier. For example, if you want to create autocomplete input box, you have to read for onchange.

Sometimes for complex forms it really get's tougher to maintain multiple ref variables but, whenever possible for small forms like search input box, login, filter you can choose not to go with onChange event and use refs.

The refs way is uncontrolled way to create components.

Thank you for reading.