Mastering React Hooks
React Hooks transformed how we write components, but how well do you actually know the mechanics behind them? Test your knowledge with these five questions, ranging from conceptual definitions to debugging broken code.
Question 1: What are Hooks in React?
What are Hooks in React?
A collection of pre-built components in React that can be easily customized and reused across multiple projects
A way to persist values between renders
Unconditional declarations about your component's needs
Special functions that allow you to get help from React
Question 2: What limitations do Hooks have?
What limitations do Hooks have?
You can't call them inside conditions, loops, or other nested functions
They can't access browser specific APIs like setInterval or window
They must start with use
They cannot access props
Question 3: What's wrong with this code?
What's wrong with this code?
export default function ToggleMessage() {
let visible = false;
const toggleVisibility = () => {
visible = !visible;
};
return (
<div>
<button onClick={toggleVisibility}>Toggle Message</button>
{visible && <p>The message is now visible!</p>}
</div>
);
}Nothing
The visible variable is not being used
The UI won't update when visible changes
visible won't persist between renders
Question 4: What does the useState Hook allow you to do?
What does the useState Hook allow you to do?
Trigger a re-render of the component
Pass data to child components
Add state to a component
Preserve a value between renders
Question 5: What's wrong with this code?
What's wrong with this code?
import * as React from "react";
export default function ThemeSwitcher() {
const [setTheme, theme] = React.useState("light")
const handleClick = () => {
setTheme(theme === "dark" ? "light" : "dark");
};
return (
<button onClick={handleClick} className={theme}>
Switch Theme
</button>
);
}Nothing
Our state destructuring is backwards
We can't use dynamic state values as className
useState returns an object, not an array