I wrap my Home component in the following layout:
export const DataContext = React.createContext({});
const Layout: React.FunctionComponent = (props) => {
const data = {title: "abc", description: "def"};
return (
<DataContext.Provider value={data}>
{props.children}
</DataContext.Provider>
);
};
I would like to use useContext hook in my Home component, but it returns an empty object:
const Home: React.FunctionComponent = () => {
const content = React.useContext(DataContext);
return (
<Layout>
// content data goes here
</Layout>
);
};
I suspected that this is because I define context variable outside of Layout wrapper, which contains context provider, so it falls back to the default value of the context that I defined (an empty object). However, even if I console log the useContext hook inside the layout provider, it also returns an empty object:
const Home: React.FunctionComponent = () => {
const content = React.useContext(DataContext);
return (
<Layout>
{console.log(React.useContext(DataContext))}
</Layout>
);
};
Any idea why?