CodePark/ questions / Hooks & custom hooks
START PRACTICINGPRACTICE
Frontend question · React › Hooks & custom hooks

user starts as null and later becomes an object. What happens?

function Profile({ user }) {
  if (!user) return <Spinner />;

  const [tab, setTab] = useState('posts');
  return <Tabs value={tab} onChange={setTab} />;
}
React throws because more hooks were rendered than during the previous render

React throws an error. The early return means the first render calls zero hooks. The next render, with a user, calls one hook. The hook order changes, and React throws because more hooks ran than during the previous render.

"Only the linter complains" is the tempting wrong answer. It is not only a lint warning, because React itself depends on the call order. Fix it by moving
useState above the early return.