I am working on a React App with latest React version. What I want to do is to call React useContext Hook in a function which is not a React Component. Can anybody please help me?
No, you cannot. From the docs
Only Call Hooks from React Functions
Instead, you can:
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks (we'll learn about them on the next page).
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
您可能需要考虑将上下文数据作为参数传递给函数,因为您无法在 React 组件之外使用 useContext 挂钩。
Like mentioned before you cannot use React Hooks outside of React, there's also not a ton of background information. What I could suggest is that you create a separate Context file importing createContext and useState from React. Then create a wrapper for further React Components
type ContextType = {
someState: stateDetails | null,
setSomeState: React.Dispatch<React.SetStateAction<stateDetails | null>>
}
type ContextProps = {
children: React.ReactNode
}
export const Context = createContext<ContextType>({} as ContextType)
export const ContextWrapper = ({ children }: ContextProps) => {
const [ someState, setSomeState ] = useState<stateDetails | null>(null)
return (
<>
<Context.Provider value={{ someState, setSomeState }}>
{children}
</Context.Provider>
</>
)
}
Then you can wrap parts of your app with the wrapper but encasing the jsx in the new wrapper component so it gets transferred around the app.
<ContextWrapper>
<OtherComponent />
</ContextWrapper>
This should be sufficient enough to create some simple context, for more advanced state handling look into Zustand or Redux . Regardless, this context can only passed into React elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.