Answers
- The problem with the component is that both
useState
anduseEffect
are called conditionally (when thetext
prop is defined), and React doesn’t allow its Hooks to be called conditionally. Placing the Hooks before theif
statement resolves the problem:export function TextVanish({ text }: Props) {
const [textToRender, setTextToRender] = useState(text);
useEffect(() => {
setTimeout(() => setTextToRender(""), 5000);
}, []);
if (!text) {
return null;
}
return <span>{textToRender}</span>;
}
- The main problem with the code is that the effect function can’t be marked as asynchronous with the
async
keyword. A solution is to revert to the older promise syntax:const [data, setData] = useState([]);
useEffect(() => {
getData().then((theData) => setData(theData));
});
The other major problem is that no dependencies...