← React Beginner Questions - Set 4 Q32
React Beginner Questions - Set 4
No — and the example shows why the answer is not 'almost': the class has no hook dispatcher, so the call fails at runtime.
// This throws: Invalid hook call.
class Legacy extends React.Component {
render() {
const [open, setOpen] = useState(false); // error
return <p>{String(open)}</p>;
}
}
// Two valid migrations
// 1. Convert to a function component
function Modern() {
const [open, setOpen] = useState(false);
return <p>{String(open)}</p>;
}
// 2. Keep the class and use state/lifecycle
class StillAClass extends React.Component {
state = { open: false };
render() { return <p>{String(this.state.open)}</p>; }
}