0
0
Reactframework~10 mins

Common lifecycle use cases in React - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a state variable using React hooks.

React
const [count, [1]] = useState(0);
Drag options to blanks, or click blank then click option'
AchangeCount
BgetCount
CupdateCount
DsetCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name that does not start with 'set'.
Confusing the updater function with the state variable.
2fill in blank
medium

Complete the code to run a side effect only once when the component mounts.

React
useEffect(() => {
  console.log('Component mounted');
}, [1]);
Drag options to blanks, or click blank then click option'
A[null]
B[]
C[true]
D[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the dependency array empty (undefined) causes the effect to run after every render.
Passing non-empty arrays causes the effect to run multiple times.
3fill in blank
hard

Fix the error in the cleanup function of useEffect to avoid memory leaks.

React
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timeout');
  }, 1000);
  return () => [1];
}, []);
Drag options to blanks, or click blank then click option'
AclearTimeout(timer)
BclearInterval(timer)
CcancelTimeout(timer)
DstopTimeout(timer)
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearInterval instead of clearTimeout.
Not returning a cleanup function at all.
4fill in blank
hard

Fill both blanks to update state and log the new value after the button click.

React
const handleClick = () => {
  setCount([1]);
  console.log('Count is now:', [2]);
};
Drag options to blanks, or click blank then click option'
Acount + 1
Bcount
Ccount - 1
DsetCount
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to log the updated count immediately after setCount (which is async).
Using setCount inside console.log.
5fill in blank
hard

Fill all three blanks to fetch data on mount and store it in state.

React
useEffect(() => {
  async function fetchData() {
    const response = await fetch([1]);
    const data = await response.[2]();
    [3](data);
  }
  fetchData();
}, []);
Drag options to blanks, or click blank then click option'
A'https://api.example.com/data'
Bjson
CsetData
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text' instead of 'json' to parse the response.
Not calling the state updater function.