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

69
Views
Implemente UseEffect de React para escuchar solo un incremento/decremento

Creé una aplicación de chat y estoy usando un useEffect para escuchar messages.length , para desplazarme hacia abajo cuando llega un nuevo mensaje, un increment en messages.length .
Sin embargo, también existe el caso en el que elimino un mensaje, una decrement en la longitud de messages.length . Es decir, también me desplazan hacia abajo al eliminarlo, y me gustaría evitar ese tipo de comportamiento. Los mensajes se almacenan en mi tienda redux y se puede acceder a ellos como accesorio.

¿Hay alguna manera de que useEffect escuche solo en un incremento?
¿Hay alguna forma de tener acceso al estado anterior de los mensajes?
¿O es inevitable almacenar una variable prevLength ?

Aquí está la parte de mi código que necesita revisión:

 // Scroll to bottom upon new message: useEffect(() => { scrollDown(); }, [messages.length]);

Este es el código completo:

 import { useState, useEffect} from 'react'; //Components: import ChatBubble from './ChatBubble'; import ScrollButton from './ScrollButton'; export default function MessagesBoard({ messages }) { //useState: const [showScrollButton, setShowScrollButton] = useState(false); //Event: Scroll to bottom upon new message useEffect(() => { scrollDown(); }, [messages.length]); const scrollDown = () => { .... }; return ( <div className='chatMessagesBlock'> <div className='messagesCanvas'> {messages.map((chatMessage) => { return ( <ChatBubble key={msgID} msgID={msgID} sender={sender} msgContent={msgContent} /> ); })} </div> <ScrollButton showScrollButton={showScrollButton} scrollDown={scrollDown} /> </div> ); }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede realizar un seguimiento de la longitud anterior en un useRef :

 const prevLength = useRef(0); useEffect(() => { if (prevLength.current < message.length) { scrollDown(); } prevLength.current = messages.length; }, [messages.length]);
about 4 years ago · Juan Pablo Isaza 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!