Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

732
Views
En general, ¿es mejor usar uno o varios ganchos useEffect en un solo componente?

Tengo algunos efectos secundarios para aplicar en mi componente de reacción y quiero saber cómo organizarlos:

  • como efecto de un solo uso
  • o varios efectos de uso

¿Cuál es mejor en términos de rendimiento y arquitectura?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

El patrón que debe seguir depende de su caso de uso.

Primero: es posible que tenga una situación en la que necesite agregar un detector de eventos durante el montaje inicial y limpiarlos al desmontarlos y otro caso en el que un oyente en particular deba limpiarse y volver a agregarse en un cambio de prop.

En tal caso, usar dos useEffect diferentes es mejor para mantener unida la lógica relevante, además de tener beneficios de rendimiento.

 useEffect(() => { // adding event listeners on mount here return () => { // cleaning up the listeners here } }, []); useEffect(() => { // adding listeners everytime props.x changes return () => { // removing the listener when props.x changes } }, [props.x])

Segundo: debe activar una llamada API o algún otro efecto secundario cuando cualquiera de los estados o accesorios cambie de un conjunto definido. En tal caso, sería mejor un solo useEffect con las dependencias relevantes para monitorear

 useEffect(() => { // side effect here on change of any of props.x or stateY }, [props.x, stateY])

Tercero: necesita un efecto secundario separado para diferentes conjuntos de cambios. En tal caso, separe los efectos secundarios relevantes en diferentes useEffect s

 useEffect(() => { // some side-effect on change of props.x }, [props.x]) useEffect(() => { // another side-effect on change of stateX or stateY }, [stateX, stateY])
over 4 years ago · Santiago Trujillo Report

0

Debe usar múltiples efectos para separar las preocupaciones como lo sugiere reactjs.org .

over 4 years ago · Santiago Trujillo Report

0

Está perfectamente bien tener múltiples useEffect.

Así es como se ve una de las configuraciones mías:

 /* * Backend tags list have changed add the changes if needed */ useEffect(() => { setTagsList(setTagsAdded); }, [setTagsAdded]); /* * Backend files have changed add the changes if needed */ useEffect(() => { for (let i = 0; i < changedFilesMeta.length; i += 1) { // Is the list item value changed if (changedFilesMeta[i].id === currentEditableFile.id) { unstable_batchedUpdates(() => { setTags(changedFilesMeta[i].tags ? changedFilesMeta[i].tags : []); }); } } }, [changedFilesMeta]); /* * Reset when user select new files using the filepicker */ useEffect(() => { if (setNewFiles.length > 0) { unstable_batchedUpdates(() => { setCurrentFile(null); setDescription(''); setTitle(''); setTags([]); }); } }, [setNewFiles]); /* * User selecet to edit a file, change to that file */ useEffect(() => { // When user select a file to edit it if (currentEditableFile && currentEditableFile !== theCurrentFile) { setCurrentFile(currentEditableFile); unstable_batchedUpdates(() => { setDescription(currentEditableFile.description); setTitle(currentEditableFile.title); setTags(currentEditableFile.tags); }); } }, [currentEditableFile]);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!