Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda