Search code examples
reactjsreact-hookschakra-ui

How to conditional render in Chakra UI?


I'm rendering two Chakra UI components based in a variable loading:

{loading ? (<Spinner>) : (<Text color={useColorModeValue('gray.800', 'gray.400')>Hi</Text) }

But the IDE is warning me about this: ESLint: React Hook "useColorModeValue" is called conditionally. React Hooks must be called in the exact same order in every component render.

How should I render those components? useColorModeValue is a hook


Solution

  • useColorModeValue is a React hook, so it can't be conditionally called, it is breaking the Rules of Hooks. Using a ternary is a way to conditionally call it. The hook must be called each and every render cycle.

    Only Call Hooks at the Top Level

    Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

    Pull the useColorModeValue out into the body of the function component and save the returned color value to be passed later to the Text component.

    const color = useColorModeValue('gray.800', 'gray.400');
    
    ...
    
    {loading ? <Spinner> : <Text color={color}>Hi</Text>}