Home > OS >  When to optimize renders in react with useMemo and useCallback
When to optimize renders in react with useMemo and useCallback

Time:02-02

I've read a few articles on when to optimize rendering in React, however, I still have some doubts.

const RepairNoticeContainer = () => {
    const dispatch = useDispatch();
    const history = useHistory();
    const { siteType, siteId } = useParams();

    const data = useSelector(pageSelectors.getData);

    const showRepairNotice = data.grid.cols.lg !== 36;

    const handleRepairClick = () => {
        dispatch(
            pagesActions.copyAndRepairCurrentPage(newPageId => {
                history.push(`/editor/${siteType}/${siteId}/pages/${newPageId}`);
            })
        );
    };

    return showRepairNotice ? <RepairNotice onRepairClick={handleRepairClick} /> : null;
};

As far as I can understand, it would be beneficial to use useCallbackfor handleRepairClick to avoid rerenders of <RepairNotice/>. But what about showRepairNoticevariable? Should it be wrapped in a useMemo for optimization?

const RepairNotice = ({ onRepairClick }) => {
    const translate = useTranslator();

    let message = translate("repair_warning");
    message = message.charAt(0).toLowerCase()   message.slice(1);

    return (
        <MessageBox type="warning" icon="information11" className="mb-0 mt-2">
            <div className="row">
                <div className="col">
                    <b>{translate("warning")}:</b> {message}
                </div>
                <div className="col-auto text-right">
                    <Button color="danger" onClick={onRepairClick} size="small">
                        {translate("repair_now")}
                    </Button>
                </div>
            </div>
        </MessageBox>
    );

A simillar question for this example. Would it be beneficial to wrap message inside of useMemo?

const Page = ({ status }) => {
    const unsavedData = status?.unsavedData ? true : false;

    return (
        <Fade>
            <div className="Page">
                <NavConfirmModal active={unsavedData} onSavePage={onSavePage} />
            </div>
        </Fade>
    );
};

Lastly, should useMemo be used unsavedData?

Explanations would be much appreciated.

CodePudding user response:

As far as I can understand, it would be beneficial to use useCallback for handleRepairClick to avoid rerenders of

That's right. while wrapping handleRepairClick you will, simply speak, prevent creating a new instance of this function so it will save RepairNotice nested component from redundant rerenders because it relies on this function in props. Another good case for useMemo is when you're rendering a list of items and each relies on the same handler function declared in their parent. Very good useCallback explanation here.

But what about showRepairNotice variable? Should it be wrapped in a useMemo for optimization?

It's just a simple "equation" check which is really cheap from performance side - so there is really no need in useMemo here.

Would it be beneficial to wrap message inside of useMemo?

Yes, it would. Since there are at least 3 actions javascript has to fire upon the message (charAt, toLowerCase, slice) and you don't really want this calculations to fire every time the RepairNotice component gets rerendered.

should useMemo be used unsavedData?

By the similar reasons of getting rid of redundant rerenders of NavConfirmModal it will be preferable to wrap unsavedData into useMemo (and it might be changed just to !!status?.unsavedData to get boolean).

And very good useMemo explanation here.

  •  Tags:  
  • Related