0
0
Reactframework~10 mins

Why custom hooks are used in React - Test Your Understanding

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

Complete the code to create a custom hook that uses state.

React
import { useState } from 'react';

function useCounter() {
  const [count, setCount] = [1](0);
  return [count, setCount];
}
Drag options to blanks, or click blank then click option'
AuseRef
BuseEffect
CuseContext
DuseState
Attempts:
3 left
💡 Hint
Common Mistakes
Using useEffect instead of useState to create state.
Trying to use useContext without a context provider.
2fill in blank
medium

Complete the code to use the custom hook inside a component.

React
function Counter() {
  const [count, setCount] = [1]();
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Drag options to blanks, or click blank then click option'
AuseCounter
BuseState
CuseEffect
DuseRef
Attempts:
3 left
💡 Hint
Common Mistakes
Calling useState directly instead of the custom hook.
Not calling the hook as a function.
3fill in blank
hard

Fix the error in the custom hook to avoid violating React rules.

React
function useCounter() {
  if (true) {
    const [count, setCount] = [1](0);
  }
  return [count, setCount];
}
Drag options to blanks, or click blank then click option'
AuseEffect
BuseState
CuseContext
DuseRef
Attempts:
3 left
💡 Hint
Common Mistakes
Calling hooks inside if statements or loops.
Trying to conditionally call hooks.
4fill in blank
hard

Fill both blanks to create a custom hook that fetches data and stores it in state.

React
import { useState, useEffect } from 'react';

function useData(url) {
  const [data, setData] = useState(null);
  useEffect(() => {
    fetch(url)
      .then(response => response.[1]())
      .then(json => setData(json));
  }, [[2]]);
  return data;
}
Drag options to blanks, or click blank then click option'
Ajson
Burl
Ctext
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using response.text() instead of response.json().
Leaving the dependency array empty or incorrect.
5fill in blank
hard

Fill all three blanks to create a custom hook that toggles a boolean state.

React
import { useState } from 'react';

function useToggle(initialValue = false) {
  const [value, setValue] = useState([1]);
  const toggle = () => setValue([2] => ![3]);
  return [value, toggle];
}
Drag options to blanks, or click blank then click option'
AinitialValue
BprevValue
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Not using the previous state in the toggle function.
Using a fixed value instead of toggling.