I am writting an React landing page, but have an error below:
4:40 error React Hook "useCreateContext" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
react-hooks/rules-of-hooks
Here is the code which may cause the problem.
import React, { useContext, createContext } from 'react';
export function useCreateContext(defaultValue, reducer) {
const defaultDispatch = () => defaultValue;
const stateCtx = createContext(defaultValue);
const dispatchCtx = createContext(defaultDispatch);
function useStateCtx(property) {
const state = useContext(stateCtx);
return state[property]; // only one depth selector for comparison
}
function useDispatchCtx() {
return useContext(dispatchCtx);
}
function Provider({ children }) {
const [state, dispatch] = React.useReducer(reducer, defaultValue);
return (
<dispatchCtx.Provider value={dispatch}>
<stateCtx.Provider value={state}>{children}</stateCtx.Provider>
</dispatchCtx.Provider>
);
}
return [useStateCtx, useDispatchCtx, Provider];
}
export const initialState = {
isSticky: false,
isSidebarSticky: true,
};
export function reducer(state, { type }) {
switch (type) {
case 'SET_STICKY':
return {
...state,
isSticky: true,
};
case 'REMOVE_STICKY':
return {
...state,
isSticky: false,
};
case 'SET_SIDEBAR_STICKY':
return {
...state,
isSidebarSticky: true,
};
case 'REMOVE_SIDEBAR_STICKY':
return {
...state,
isSidebarSticky: false,
};
default: {
throw new Error(`Unsupported action type: ${type}`);
}
}
}
const [state, useDispatch, provider] = useCreateContext(initialState, reducer);
export const useStickyState = state;
export const useStickyDispatch = useDispatch;
export const StickyProvider = provider;
Then I use the StickProvider in the home page.
export default function IndexPage() {
return (
<StickyProvider>
<Layout>
<SEO title="Startup Landing 005" />
<Banner />
<KeyFeature />
<ServiceSection />
<Feature />
<CoreFeature />
<WorkFlow />
<Package />
<TeamSection />
<TestimonialCard />
<BlogSection />
<Subscribe />
</Layout>
</StickyProvider>
);
}
Can anyone help with how to fix this error?
2
Answers
you have to call this
const [state, useDispatch, provider] = useCreateContext(initialState, reducer);
inside the function not outside you are breaking hooks rule.
The way you are doing outside function it’s wrong
You should rename useCreateContext to another not including "use" prefix because now is a reserved word in react, the same case with "set".