DEV Community

Cover image for Using composition to optimize React rendering
coder4life
coder4life

Posted on

Using composition to optimize React rendering

How you can improve and minize re-rendering in your React app using component composition. It's really simple. Here we refactor a simple app that re-renders a third component not related to the changes happening.


import { useCallback, useState } from 'react';

function App() {
    return (
        <div className="app">
            <CounterComponent>
                <Title />
            </CounterComponent>
        </div>
    );
}

const CounterComponent = ({ children }) => {
    const [count, setCount] = useState(0);

    const increment = useCallback(() => {
        setCount(prev => prev + 1);
    }, []);

    const decrement = useCallback(() => {
        setCount(prev => prev - 1);
    }, []);

    console.log('render CounterComponent');

    return (
        <div>
            {children}
            <h2>{count}</h2>
            <div>
                <button onClick={decrement}>-</button>
                <button onClick={increment}>+</button>
            </div>
        </div>
    );
};

const Title = () => {
    console.log('render Title');
    return <h1>Counter</h1>;
};

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)