I’m studing React and got a question about ‘Why React Hooks must be used inside function components’
I wrote useContext
outside of the function components by mistake, and got a error message.
React Hook "useContext" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.
I thought maybe it is to manage sequence for calling hooks, and I read React docs to find out exact reason.
But only I can find was ‘call them at the top level in the body of a function component’ line.
I know it’s very silly question to ask but I can’t find nice reason to make me understand.
I’d really appreciate your help.
2
Answers
You are correct, React stores hooks in array under the hood, there’s still valid explanation here:
They need to be used inside components because they are directly tied to an instance of a component.
For example,
useState
creates a state of that component instance. Calling use state outside a component wouldn’t have any effect, because there is no component instance for the state to be associated with.useContext
tells react to search upward in the component tree for a context provider of the correct type, and give you its value. This is relative to the current component’s spot in the component tree. If you called it outside a component, there is no component instance from which to start the search.