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

171
Visualizações
React Hooks - Prevent re-render when using prevState

I would like to be able to conditionally set a state based on previous state changes with React Hooks. But if the state remains the same the component shouldn't re-render.

When using class components, I was able to achieve this using:

this.setState(prevState => {
   if(prevState.value !== true) {
     return { value: true }
   }

   return null
})

The code above sets the state to true, only if it's not true. However, if it's already true, the component doesn't re-render. I would like to achieve the same effect with React Hooks.

I know that with React Hooks, I can use the prevState like this:

setValue(prevValue => {
   // some code
   return newValue
})

However, I don't know how to prevent re-render if the state remains the same. Is it possible for me to prevent render after using React Hooks prevState? Thank you for your concern.

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

0

Two ways:

  1. Use of pure components using life cycle hooks or useMemo in React Hooks.
  2. shouldComponentUpdate() use the change of state login inside this hook.
about 4 years ago · Juan Pablo Isaza Relatório

0

Wrap your component by memo

import { useEffect, useState, memo } from "react";

const App = () => {
  const [test, setTest] = useState(false);

  useEffect(() => {
    console.log("re-rendered");
  });

  const setTestToTrue = () => {
    setTest((v) => {
      if (v !== true) return true;
      return v;
    });
  };

  return (
    <div className="App">
      <button onClick={setTestToTrue}>Set test to true</button>
    </div>
  );
};

export default memo(App);

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