stackuser
stackuser

Reputation: 219

How to use one useMemo using react?

i want to use only one useMemo instead of two useMemo in one component.

below is my code,

const App = () => {
    const isChecked = React.useMemo(() => 
        checked === 'something', [checked]);
    const variables = React.useMemo(() => ({
        variable1,
        variable2: 200
    }), [variable1]);

    return (
        //some jsx
    ); 
}

now the question is how can i combine the above two useMemo into one. could someone help me with this. thanks.

Upvotes: 0

Views: 84

Answers (1)

TheTisiboth
TheTisiboth

Reputation: 1651

You can use the array destructuration like this :

const [isChecked, variables] = React.useMemo(() => [
checked === 'something', 
{ variable1, variable2: 200 }], 
[checked, variable1]);

However, it is less optimized, since if either checked or variable1 change, it will re execute the useMemo function for both of the variables isChecked and variables

Upvotes: 2

Related Questions