Skip to content

Commit

Permalink
some simple examples of preventing re-renders due to store changes
Browse files Browse the repository at this point in the history
just doing "Option 3" from [this comment](facebook/react#15156), which is just about using useMemo. unfortunately this is not an easy pattern to encapsulate, because you can't call hooks from inside other hooks: https://gist.github.com/levity/3ab3e0f88fd28d55fde5444b9d482f98
  • Loading branch information
levity committed May 22, 2019
1 parent d7a06ee commit 2777d89
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 19 deletions.
39 changes: 29 additions & 10 deletions src/components/Sidebars/Global.js
Expand Up @@ -4,19 +4,38 @@ import SidebarSystem from 'components/SidebarSystem';
import { Box, Grid } from '@makerdao/ui-components-core';
import { getAllFeeds } from 'reducers/feeds';
import useStore from 'hooks/useStore';
import { ETH } from '@makerdao/dai-plugin-mcd';

const SidebarGlobalPanel = () => {
const [{ system, feeds }] = useStore();
const uniqueFeeds = useMemo(() => getAllFeeds(feeds), [feeds]);

return (
<Box>
<Grid gridRowGap="s">
<SidebarFeeds feeds={uniqueFeeds} />
<SidebarSystem system={system} />
</Grid>
</Box>
);
return useMemo(() => {
console.log('SidebarGlobalPanel rendering');
const uniqueFeeds = getAllFeeds(feeds, [feeds]);
return (
<Box>
<Grid gridRowGap="s">
<SidebarFeeds feeds={uniqueFeeds} />
<SidebarSystem system={system} />
</Grid>
<Dev />
</Box>
);
}, [system, feeds]);
};

export default SidebarGlobalPanel;

const Dev = () => {
const [, dispatch] = useStore();

window.randomizeEthPrice = () => {
const num = 200 + Math.random() * 50;
dispatch({ type: 'ETH.feedValueUSD', value: ETH(num) });
};

window.updateCdps = () => {
dispatch({ type: 'cdps/FETCHED_CDPS', payload: { cdps: [] } });
};

return null;
};
23 changes: 14 additions & 9 deletions src/pages/CDP.js
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import styled from 'styled-components';
import { hot } from 'react-hot-loader/root';
import PageContentLayout from 'layouts/PageContentLayout';
Expand Down Expand Up @@ -257,18 +257,23 @@ function CDPView({ cdpId: _cdpId }) {
})();
}, [cdpId, feeds, maker]);

return cdp ? (
<CDPViewPresentation
cdp={cdp}
showSidebar={showSidebar}
account={account}
/>
) : (
<LoadingLayout />
return useMemo(
() =>
cdp ? (
<CDPViewPresentation
cdp={cdp}
showSidebar={showSidebar}
account={account}
/>
) : (
<LoadingLayout />
),
[cdp, showSidebar, account]
);
}

function CDPViewPresentation({ cdp, showSidebar, account }) {
console.log('CDPViewPresentation rendering');
const liquidationPrice = round(cdp.liquidationPrice.toNumber(), 2).toFixed(2);
const gem = cdp.type.currency.symbol;
const collateralPrice = round(cdp.collateralPrice.toNumber(), 2);
Expand Down

0 comments on commit 2777d89

Please sign in to comment.