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

135
Views
Cómo usar la devolución de llamada `setState` en ganchos de reacción

React hooks introduce useState para establecer el estado del componente. Pero, ¿cómo puedo usar ganchos para reemplazar la devolución de llamada como el siguiente código?

 setState( { name: "Michael" }, () => console.log(this.state) );

Quiero hacer algo después de que se actualice el estado.

Sé que puedo usar useEffect para hacer las cosas adicionales, pero tengo que verificar el valor anterior del estado que requiere un código de bits. Estoy buscando una solución simple que pueda usarse con useState hook.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Necesita usar useEffect hook para lograr esto.

 const [counter, setCounter] = useState(0); const doSomething = () => { setCounter(123); } useEffect(() => { console.log('Do something after counter has changed', counter); }, [counter]);

Si desea que se ignore la devolución de llamada useEffect durante el primer procesamiento inicial , modifique el código en consecuencia:

 import React, { useEffect, useRef } from 'react'; const [counter, setCounter] = useState(0); const didMount = useRef(false); const doSomething = () => { setCounter(123); } useEffect(() => { // Return early, if this is the first render: if ( !didMount.current ) { return didMount.current = true; } // Paste code to be executed on subsequent renders: console.log('Do something after counter has changed', counter); }, [counter]);
over 4 years ago · Santiago Trujillo Report

0

Si desea actualizar el estado anterior, puede hacer esto en ganchos:

 const [count, setCount] = useState(0); setCount(previousCount => previousCount + 1);
over 4 years ago · Santiago Trujillo Report

0

setState devolución de llamada de setState con useEffect , solo activando actualizaciones de estado (no estado inicial):

 const [state, setState] = useState({ name: "Michael" }) const isFirstRender = useRef(true) useEffect(() => { if (isFirstRender.current) { isFirstRender.current = false // toggle flag after first render/mounting return; } console.log(state) // do something after state has updated }, [state])

Hook personalizado useEffectUpdate

 function useEffectUpdate(callback) { const isFirstRender = useRef(true); useEffect(() => { if (isFirstRender.current) { isFirstRender.current = false; // toggle flag after first render/mounting return; } callback(); // performing action after state has updated }, [callback]); } // client usage, given some state dep const cb = useCallback(() => { console.log(state) }, [state]); // memoize callback useEffectUpdate(cb);
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!