Search code examples
javascriptreactjsreact-hooksreact-contextuse-context

React useContext Returning Undefined


struggling to with react contexts being used with functional components. I feel like I'm doing everything right here, so any help would be much appreciated.

First I define a context (HeaderHoverContext.js)

import React, { createContext, useState } from "react";

export const HeaderHoverContext = createContext();

export function HeaderHoverProvider(props) {
    const [currentHover, setHover] = useState(false);
    const toggleHover = (e) => {
        setHover(true);
    }
    return (
        <HeaderHoverContext.Provider value={{currentHover, toggleHover}}>
            {props.children}
        </HeaderHoverContext.Provider>
    );
}

I wrap the provider within my header (Header.js)

import React, { Component, useContext } from 'react'
import './header.css'
import Headerbutton from './Headerbutton';
import Hoverviewcontainer from './Hoverviewcontainer'
import {HeaderHoverProvider} from './contexts/HeaderHoverContext'

export default function Header() {
    return (
            <div className='header'>
                <div className='header-right'>
                    <HeaderHoverProvider>
                        <Headerbutton text="Misc1" id="misc1" />
                        <Headerbutton text="Misc2" id="misc2" />
                        <Hoverviewcontainer id="misc3"/>
                        <Hoverviewcontainer id="misc4"/>
                    </HeaderHoverProvider>
                </div>
            </div>
    );
}

Any then lastly, I try to retrieve the context using the useContext hook, but sadly its undefined.

import React, { useContext } from 'react'
import { HeaderHoverContext } from "./contexts/HeaderHoverContext";

export default function Hoverviewcontainer(props) {

    const { isHover, setHover } = useContext(HeaderHoverContext);

    // Returns undefined
    console.log(`Current hover value is ${isHover}`)

    return (
        <div className={props.isHover ? 'hidden' : 'nothidden'} onMouseEnter={setHover}>
            <div className="caret" id={props.id}/>
        </div>
    )
}

Any ideas what I might be missing here?


Solution

  • The fields in your context aren't called isHover and setHover, they are called currentHover and toggleHover, so either use them in the destructor or destruct manually:

      const context = useContext(HeaderHoverContext);
      const isHover = context.currentHover;
      const setHover = context.toggleHover;
    

    By the way, your toggle hover has a bug, never sets it to false. Try this instead:

    const toggleHover = () => setHover(current => !current);