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

161
Vistas
Is there a refactoring pattern to avoid infinite re-renders due to identic data perpetually jumping between parent to child?

Imagine a simple part of a React application that consists of OuterComponent and InnerComponent inside of it. There are instructions these components must follow:

  • Whenever the data in OuterComponent changes its value, it must overwrite InnerComponent's localData's current value.
  • Whenever the localData in InnerComponent changes its value, it must overwrite OuterComponent's data's current value.

Here is the code in question:

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

const InnerComponent = ({ data = [], onChange = null }) => {
  const [localData, setLocalData] = useState([]);

  useEffect(() => {
    if (onChange) onChange(localData);
  }, [localData, onChange]);

  useEffect(() => {
    console.log("render");
    setLocalData(data);
  }, [data]);

  return (
    <div>
      {localData.map((e) => (
        <div>{e}</div>
      ))}
    </div>
  );
};

const OuterComponent = () => {
  const [data, setData] = useState(["alice", "bob"]);

  return <InnerComponent data={data} onChange={setData} />;
};

export default function App() {
  return (
    <div className="App">
      <OuterComponent />
    </div>
  );
}

Since this situation is something which can arise in a lot of cases and thus is typical, are there any existing time-honored ways of refactoring that code into something free from potential infinite rendering cases? I'm also curious whether there is a way if localData is an array while data is an object that has this array in one of its keys which should be monitored by a child component.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Yes, in such cases I'd keep a ref of the previous localData in the InnerComponent and add a guard clause, in the useEffect that calls onChange, to test against current localData e.g.:

const prevLocalData = useRef(localData);
useEffect(() => {
  if (JSON.stringify(localData) === JSON.stringify(prevLocalData.current)) {
    return undefined;
  }

  onChange(localData);
}, [localData, onChange])
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