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

201
Views
React Hook "React.useState" no se puede llamar dentro de una devolución de llamada. React Hooks debe llamarse en un componente de función React

Estoy tratando de crear un estado predeterminado basado en el contexto del usuario, pero no pude usar el contexto fuera de la devolución de llamada de <myContext.Consumer>{myContext => {}}</myContext.Consumer> . Recibo el error anterior cuando intento usar setState en la devolución de llamada

Aquí está mi caso de uso:

 import * as React from 'react' import Box from '@mui/material/Box' import PageTitle from '../01_shared/PageTitle' import { appCtx } from '../01_shared/appContext' const MyComponent = () => { const [options, setOptions] = React.useState({ currency: userContext.currency, // <=I need user context information here }) return <appCtx.Consumer>{translationContext => { // I cannot use React.useState here return ( <Box> <PageTitle>Hello {userCtx.firstName} you have 3 {options.currency}</PageTitle> </Box> ) }}</appCtx.Consumer> }; export default MyComponent

Sé que puedo establecer el estado directamente después de tener acceso al userContext de usuario, pero parece más una solución alternativa que una solución adecuada.

¿Podría indicarme la dirección correcta, por favor?

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

0

Los componentes de la función pueden usar el useContext para obtener valores de contexto y, por lo tanto, no es necesario representar un <appCtx.Consumer> :

 const MyComponent = () => { const userContext = React.useContext(appCtx); const [options, setOptions] = React.useState({ currency: userContext.currency, }); return ( <Box> <PageTitle> Hello {userContext.firstName} you have 3 {options.currency} </PageTitle> </Box> ); };
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!