Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
When to optimize renders in react with useMemo and useCallback

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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?

It might be preferable to wrap unsavedData into useMemo if NavConfirmModal will be wrapped in React.Memo or in the case of "heavy calculations". So for the current case - it would not really make a difference. (btw calculating unsavedData could be written just like !!status?.unsavedData to get boolean).

And very good useMemo explanation here.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda