Search code examples
reactjsapollo-clientreact-memo

How can I force update React.memo child component?


My main functional component performs a huge amount of useQueries and useMutations on the child component hence I have set it as React.memo so as to not cause re-rendering on each update. Basically, when new products are selected I still see the old products because of memo.

mainFunction.js

const [active, setActive] = useState(false);
const handleToggle = () => setActive(false);

const handleSelection = (resources) => {
        const idsFromResources = resources.selection.map((product) => product.variants.map(variant => variant.id));
        store.set('bulk-ids', idsFromResources); //loal storage js-store library
        handleToggle
    };
    
const emptyState = !store.get('bulk-ids'); // Checks local storage using js-store library
    
return (
    <Page>
        <TitleBar
            title="Products"
            primaryAction={{
                content: 'Select products',
                onAction: () => {
                    setActive(!active)
                }
            }}
        />
        <ResourcePicker
            resourceType="Product"
            showVariants={true}
            open={active}
            onSelection={(resources) => handleSelection(resources)}
            onCancel={handleToggle}
        />
        <Button >Add Discount to Products</Button> //Apollo useMutation

        {emptyState ? (
            <Layout>
                Select products to continue
            </Layout>
        ) : (
                <ChildComponent />
            )}
    </Page>
    );
    
    

ChildComponent.js

class ChildComponent extends React {
    return(
        store.get(bulk-ids).map((product)=>{
            <Query query={GET_VARIANTS} variables={{ id: variant }}>
                {({ data, extensions, loading, error }) => {
                    <Layout>
                        // Query result UI
                    <Layout>
                }}
            </Query>
        })
    )
}
export deafult React.memo(ChildComponent);
    

Solution

  • React.memo() is useful when your component always renders the same way with no changes. In your case you need to re-render <ChildComponent> every time bulk-id changes. So you should use useMemo() hook.

    function parentComponent() {
     
        ... rest of code
    
        const bulkIds = store.get('bulk-ids');
        const childComponentMemo = useMemo(() => <ChildComponent ids={bulkIds}/>, [bulkIds]); 
    
        return <Page>
            
            ... rest of render
            
            {bulkIds ? 
                childComponentMemo
            :(
                <Layout>
                    Select products to continue
                </Layout>
            )}        
        </Page>
        
    }
    

    useMemo() returns the same value until buldIds has not changed. More details about useMemo() you can find here.