
28 min
You Can’t Use Hooks Conditionally… or Can You?
It’s the hooks rule number one: “Only call hooks at the top level”.
But what if I told you that this rule does not apply to every hook? One of them can actually safely be used conditionally.
To understand how useContext is different from other hooks, and why it is exempted from this major rule, we need to know why this rule exists in the first place. We will build our own mental model of react’s rendering behavior, focused on how react keeps track of data at runtime: props, states, refs… and context values.
But what if I told you that this rule does not apply to every hook? One of them can actually safely be used conditionally.
To understand how useContext is different from other hooks, and why it is exempted from this major rule, we need to know why this rule exists in the first place. We will build our own mental model of react’s rendering behavior, focused on how react keeps track of data at runtime: props, states, refs… and context values.