Home > database >  Most performant way to declare components in React
Most performant way to declare components in React

Time:09-13

I lack an understanding of how the React framework works under the hood, and could use some clarification. Particularly how React optimizes the update process of the DOM (by determining which part of the DOM has actually changed between renders).

For example, what is the difference between implementation A and B?

Implementation A:

// ParentComponent.js
function ParentComponent(props) {
    
    const [clicks, setClicks] = useState(0);
    
    const ChildComponent = (props) => {
        return (
            <div>
                child component
            </div>
        )
    }

    return (
        <div>
            <button onClick={() => setClicks(clicks   1)}>Click Me</button>
            <ChildComponent />
        </div>
    )
}

Implementation B:


// ChildComponent.js
const ChildComponent = (props) => {
    return (
        <div>
            child component
        </div>
    )
}

// ParentComponent.js
import ChildComponent from './ChildComponent.js'

function ParentComponent(props) {

    const [clicks, setClicks] = useState(0);

    return (
        <div>
            <button onClick={() => setClicks(clicks   1)}>Click Me</button>
            <ChildComponent />
        </div>
    )
}

The way I see it, every time implementation A re-renders the <ParentComponent> (via a state change) it will redeclare the function which returns JSX for the <ChildComponent/>, meaning even though nothing ever changes to the <ChildComponent> between renders, React would still re-render that component, no?

On the other hand, I don't really know how implementation B is any different

  • Related