Skip to main content

Command Palette

Search for a command to run...

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

Updated
2 min read
Improving performance of React component | using less state variables

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.

F

An awesome library I love using when it comes to handling forms is the react-hook-form library. It makes things a lot easier and also makes use of ref behind the scene.

A

Hello 👋

Thanks for the article, but IMHO this shouldn't be used as an approach to what React could "control" - Controlled vs. Uncontrolled components.

We are losing other possibilities like instant validation, conditional work with input(show/hide/disable something), formatting(like a phone), several values for different inputs, etc. You would still need to handle additional events and via value + onChange is better than direct DOM manipulation.

UPDATE for the last paragraph: These re-render are expected, such you have changed input 7 times - this is how reconciliation works.

PREVIOUS general knowledge: Also, re-renders could happen from something above in most cases: providers, settings, stores, etc. - you could avoid this by doing memorizing for components with unchanged props if you need (but in general, these updates don't have such impacts on performance and we let React do its work).

3
A

I agree with you Andrii. If we move away from react's way to handle forms, we loose a lot of power.

The use case of ref would be very limited.

1