简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM