skip to Main Content

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


  1. You are correct, React stores hooks in array under the hood, there’s still valid explanation here:

    React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components).
    There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search