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

219
Views
React Hook "React.useState" cannot be called inside a callback. React Hooks must be called in a React function component

I am trying to make a default state based on user context but I couldn't get to use context outside tha callback of <myContext.Consumer>{myContext => {}}</myContext.Consumer>. I get the above error when I try to use setState in the callback

Here is my use case:

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

I know I can set the state straight after having access to the userContext but that seem more like a workaround than a proper solution.

Could you point me to the right direction please ?

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

0

Function components can use the useContext hook to get context values, and thus you don't need to render an <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!