0
0
Reactframework~10 mins

Custom hook best practices 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 custom hook that uses React's useState.

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'
AuseEffect
BuseRef
CuseContext
DuseState
Attempts:
3 left
💡 Hint
Common Mistakes
Using useEffect instead of useState for state management.
Trying to use useRef to hold state that triggers re-render.
2fill in blank
medium

Complete the code to ensure the custom hook returns a memoized callback.

React
import { useCallback } from 'react';

function useLogger() {
  const log = [1](() => {
    console.log('Logging');
  }, []);
  return log;
}
Drag options to blanks, or click blank then click option'
AuseCallback
BuseMemo
CuseEffect
DuseState
Attempts:
3 left
💡 Hint
Common Mistakes
Using useMemo instead of useCallback for functions.
Not memoizing the function causing unnecessary re-renders.
3fill in blank
hard

Fix the error in the custom hook by completing the missing import.

React
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

export default useWindowWidth;

// Missing import: import [1] from 'react';
Drag options to blanks, or click blank then click option'
AuseEffect
BuseState
CuseCallback
DuseRef
Attempts:
3 left
💡 Hint
Common Mistakes
Importing useEffect but forgetting useState.
Not importing any hooks causing runtime errors.
4fill in blank
hard

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

React
import { useState, [1] } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = [2](true);

  // fetching logic here
}
Drag options to blanks, or click blank then click option'
AuseEffect
BuseState
CuseCallback
DuseRef
Attempts:
3 left
💡 Hint
Common Mistakes
Using useCallback instead of useEffect for fetching.
Not initializing loading state with useState.
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'
Atrue
Bprev
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing with true instead of false.
Not using the previous state in the toggle function.