最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to return everything from one useMemo using react? - Stack Overflow

programmeradmin1浏览0评论

i want to use one useMemo instead of many React.useMemo blocks.

below is my code,

const App = () => {
    const isChecked = React.useMemo(() => {
        const source = get(data, 'somesource');
        return source === 'source1' ||
            source === 'source2';
    }, [data]);
    const details = React.useMemo(() => {
        return get(data, 'details');
    }, [data]);
    const types = React.useMemo(() => {
        return get(data, 'types', []);
    }, [data]);
   
    return (
        //some jsx
    );
}

How can i rewrite the above code to use one useMemo. could someone help me with this. i am new to using react. thanks.

i want to use one useMemo instead of many React.useMemo blocks.

below is my code,

const App = () => {
    const isChecked = React.useMemo(() => {
        const source = get(data, 'somesource');
        return source === 'source1' ||
            source === 'source2';
    }, [data]);
    const details = React.useMemo(() => {
        return get(data, 'details');
    }, [data]);
    const types = React.useMemo(() => {
        return get(data, 'types', []);
    }, [data]);
   
    return (
        //some jsx
    );
}

How can i rewrite the above code to use one useMemo. could someone help me with this. i am new to using react. thanks.

Share Improve this question asked Feb 10, 2021 at 20:41 stackuserstackuser 2191 gold badge5 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Like any react hook, you can return an array of values or an object of values from useMemo.

Array version

const App = () => {
    const [isChecked, details, types] = React.useMemo(() => {
        const source = get(data, 'somesource');
        const details = get(data, 'details');
        const types = get(data, 'types', []);

        return [source === 'source1' || source === 'source2', details, types];
    }, [data]);

    return (
        //some jsx
    );
}

Object version

const App = () => {
    const {isChecked, details, types} = React.useMemo(() => {
        const source = get(data, 'somesource');
        const details = get(data, 'details');
        const types = get(data, 'types', []);

        return {
            isChecked = (source === 'source1' || source === 'source2'),
            details,
            types
        };
    }, [data]);

    return (
        //some jsx
    );
}
发布评论

评论列表(0)

  1. 暂无评论