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

355
Views
React Hook: setData con función pura para usar prevData pero con una comparación profunda en el interior

Tengo el siguiente código:

 export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} > {children} </CurrentUserContext.Provider> ); }

y estoy haciendo lo siguiente para actualizar los datos:

 const currentUser = useContext(CurrentUserContext); currentUser.setData((prevData) => { ...prevData, totalFollowers: prevData.totalFollowers + 1 });

Ahora necesito evitar actualizaciones de estado innecesarias. Pero también necesito poder acceder a la función pura setData.

Mi idea era comparar en profundidad el nuevo objeto de datos, actualizando mi CurrentUserProvider:

 export function CurrentUserProvider({ children }) { const [data, _setData] = useState(undefined); const setData = (newData) => { if(!lodash.isEqual(newData, data)) { setData(newData); } } return ( <CurrentUserContext.Provider value={{ data, setData, }} > {children} </CurrentUserContext.Provider> ); }

Pero... con esto, no puedo acceder a prevData. ¿Algunas ideas?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Realice la verificación de igualdad dentro de la devolución de llamada setState y, si son iguales, devuelva el estado anterior. Según los documentos :

Si su función de actualización devuelve exactamente el mismo valor que el estado actual, la representación posterior se omitirá por completo.

 export function CurrentUserProvider({ children }) { const [data, _setData] = useState(undefined); const setData = useCallback(newData => { _setData(prevData => lodash.isEqual(newData, prevData) ? prevData : { ...prevData, ...newData } ); }, []); return ( <CurrentUserContext.Provider value={{ data, setData, }} > {children} </CurrentUserContext.Provider> ); }
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!