TOPKAT
TOPKAT

Reputation: 8698

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 ?

Upvotes: 0

Views: 4159

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85251

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>
  );
};

Upvotes: 1

Related Questions