React Hooks and Custom Hooks

COURSE 6 – ADVANCED REACT QUIZ ANSWERS

Week 2: React Hooks and Custom Hooks

Meta Front-End Developer Professional Certificate

Complete Coursera Answers & Study Guide

Click to Enroll in Coursera Meta Front-End Professional Certificate

React Hooks and Custom Hooks INTRODUCTION

React Hooks, and Custom Hooks are essential components of React applications, and learning how to use them can be a daunting task. However, Coursera’s Meta Front-End Developer Professional Certificate provides comprehensive instruction on React Hooks and Custom Hooks. Through this program, users will learn the basics of React Hooks and how to use them within their own React applications.

Additionally, they’ll also get hands-on practice in developing their own custom hooks to fit any specific needs of the application. By completing this coursework, developers will have a deep understanding of React Hooks and Custom Hooks, allowing them to confidently build complex React apps.

Learning Objectives

  • Explain the uses and purpose of React hooks.
  • Use the useState hook to declare, read and update the state of a component.
  • Use the useEffect hook to perform side-effects within a React component.
  • Use hooks to fetch data in React.
  • Create appropriate custom hooks in React.

SELF-REVIEW: MANAGING STATE WITHIN A COMPONENT

1. Is this a valid useState hook invocation and destructuring?

const [car, setCar] = useState({ color: 'blue', mileage: 0})
  • Yes (CORRECT)
  • No
  • It would be valid, if it was spread over multiple lines.

Correct: Correct. This code shows a valid call to the useState() hook. It’s also correctly destructured to car and setCar.

2. True or False: You can clone a JS object using the . operator (the dot operator).

  • True
  • False (CORRECT)

Correct: Correct. The dot operator is not used to clone an object in JS.

3. Consider the following code:

 const [person, setPerson] = useState({ name: 'John', age: 21})

Imagine you’re using a setPerson() state-updating function to update the value of the state variable named person. You only want to update the value of age, from 21 to 22. Choose the correct code snippet to do that.

  • setPerson(prev => ({ ...prev, age: 22 })); (CORRECT)
  • setPerson(() => ({ age: 22 }));
  • setPerson(person.age = 22);

Correct: Yes, this snippet is correct, because it clones the previous state object, and updates only the cloned object’s age value.

KNOWLEDGE CHECK: GETTING STARTED WITH HOOKS

1. Imagine you have to log into the console a state variable, whenever the variable gets updated. What’s the best place to perform such operation in a React component?

  • Before the return statement of the component
  • the useEffect hook (CORRECT)

Correct: Correct! All side effects should be inside the useEffect hook.

2. The useEffect hook accepts…

  • a callback function and an array (CORRECT)
  • two callback functions 
  • a callback function and an object

Correct: That’s correct! The useEffect hook accepts a callback function and an array.

3. What is a pure React component?

  • A component that doesn’t have any side effects (CORRECT)
  • A component that has at least one side effect

Correct: Correct. A pure component doesn’t present any side effects

4. What is the name of the second argument of the useEffect() call?

  • the dependency array (CORRECT)
  • the callback function 
  • the destructured object 
  • the dependencies object 

Correct: Correct! The name of the second argument is the dependency array.

5. This code is incomplete:

React.useEffect(()=> {
 console.log('The value of the toggle variable is',toggle)
}, [])

You need to update the dependecies array so that the useEffect hook is invoked whenever the toggle variable updates. Choose the correct solution from the choices below.

  • The dependencies array should receive the toggle variable as its single member. (CORRECT)
  • The dependencies array should be removed. 
  • The dependencies array should be updated to: [{toggle}]. 
  • The dependencies array should be replaced with: {toggle}. 

Correct: Correct. The dependencies array should receive the toggle variable as its single member: [toggle].

SELF-REVIEW: CAN YOU FETCH DATA?

1. True or False: When invoking the fetch() function to get some JSON data from an API, you should pass it a URL.

  • True (CORRECT)
  • False

Correct: Correct! When invoking the fetch() function to get some JSON data from an API, you should pass it a URL.

2. True or False: After invoking the fetch() function, you need to add a call to the then() function.

  • True (CORRECT)
  • False

Correct: Yes, it is correct that you need to add a call to the then() function after invoking the then() function.

3. Choose the right way to handle the response from a fetch call.

  • then( response => response.json()) (CORRECT)
  • then( response => json() )
  • then( json => response()

Correct: Correct. This is the right way to handle the response from a fetch call.

KNOWLEDGE CHECK: RULES OF HOOKS AND FETCHING DATA WITH HOOKS

1. True or false: You should not call hooks inside loops.

  • True (CORRECT)
  • False

Correct: Correct! You should not call hooks inside loops.

2. True or false: You should call hooks inside if statements.

  • True 
  • False (CORRECT)

Correct: Correct! You should not call hooks inside if statements.

3. True or false: You should call hooks inside nested functions.

  • True 
  • False (CORRECT)

Correct: Correct! You should not call hooks inside nested functions.

4. You are allowed to:

  • call multiple state hooks and effect hooks inside a component (CORRECT)
  • only call a single effect hook inside a component. 
  • only call a single state hook inside a component 

Correct: That’s right! You can call multiple state hooks and effect hooks inside a component.

5. True or false: You don’t have to always make multiple hook calls in the same sequence.

  • True 
  • False (CORRECT)

Correct: Correct. If you’re making multiple hook calls, you always need to call them in the same sequence. You do have to always make multiple hook calls in the same sequence.

SELF-REVIEW: CREATE YOUR OWN CUSTOM HOOK, USEPREVIOUS

1. True or False: You code a custom hook when you want to avoid duplication.

  • True (CORRECT)
  • False

Correct: Yes, it is correct that you code a custom hook when you want to avoid duplication.

2. Let’s imagine you code a custom hook, called for example useNext, on a separate file named useNext.js. What’s the minimum requirement for the custom useNext hook to be a valid hook?

  • The custom hook should always return a value
  • The custom hook should use at least one built-in React hook (CORRECT)
  • The custom hook should always receive a parameter

Correct: Correct, that’s the minimum requirement for the custom hook to be valid

3. In the previous exercise, you were given a task to create your own custom hook, usePrevious. What was being returned from the usePrevious function declaration?

  • ref.current (CORRECT)
  • ref
  • current

Correct: Correct. The value that needed to be returned from the usePrevious hook was the current property on the ref object.

KNOWLEDGE CHECK: ADVANCED HOOKS

1. True or false: useReducer is a reducer function that takes in the initial state and an action and returns the new state.

  • True (CORRECT)
  • False

Correct: Correct! The reducer function takes in the initial state and an action and returns the new state.

2. True or false: The useState hook is best suited for complex state logic or when the next state depends on the previous one.

  • True 
  • False (CORRECT)

Correct: Correct! Actually, the useReducer hook is better suited for those use-cases

3. A common scenario for using the useRef hook is to…

  •  …focus the cursor into an input field. (CORRECT)
  •  …control a component’s state. 
  •  …handle side effects. 
  • …memorize expensive operations. 

Correct: Correct. That’s a “textbook example” of the useRef hook in use.

4. True or false:  Building your own Hooks lets you extract component logic into reusable functions 

  • True (CORRECT)
  • False 

Correct: Correct! This is a true statement.

5. The useState hook gives us a reliable way to…

  • … deal with state updates in React components. (CORRECT)
  • … deal with state updates in React prompts. 
  • … deal with state updates in React dependency arrays. 
  • … deal with state updates in React useEffect invocations. 

Correct: Correct! Indeed, the useState hook gives us a reliable way to deal with state updates in React components.

Coursera Meta Front-End Developer Professional Certificate Answers and Study Guide

Liking our content? Then don’t forget to ad us to your bookmarks so you can find us easily!

Weekly Breakdown | Meta Study Guides | Back to Top

MODULE QUIZ: REACT HOOKS AND CUSTOM HOOKS

1. How is array destructuring relevant to hooks in React?

  • It makes it possible to handle click events. 
  • It is a way to get individual items from an array of items, and save those individual items as separate components. (CORRECT)
  • It makes the Virtual DOM possible. 
  • It makes it possible to reassign state objects. 

Correct: Correct. It is a way to get individual items from an array of items, and save those individual items as separate components.

2. Is the following paragraph correct?

With array destructuring, you are free to give any variable name to the items that you destructure from an array. Contrary to that, when destructuring objects, you have to destructure a property of an object using that exact property’s name as the name of the destructured variable.

  • Yes (CORRECT)
  • No

Correct: That’s right, the paragraph is correct.

3. The useEffect hook is a way to:

  • handle a side effect. (CORRECT)
  • handle one-way data flows 
  • handle visual effects (animations and transitions) in React 

Correct: That’s correct! The name of the useEffect hook is closely related to the concept of an effect, or more precisely, of a side effect.

4. Which answer is correct about the following code snippet?

useEffect( () => {
  if (data !== '') {
    setData('test data')
  }
})
  • This code is breaking the rules of hooks 
  • This code is not breaking the rules of hooks (CORRECT)
  • This code is ok, except the fact that you should replace the if statement with a ternary operator.

Correct: Correct. The code snippet is valid.

5. Choose an example of a side-effect with which you’d need to use a useEffect hook:

  • Run a Fetch API call in React. (CORRECT)
  • Update the value of the state variable in a child component. 
  • Render some prop values on the screen.

Correct: Correct. The call to the Fetch API is a side-effect, and you should use the useEffect hook to handle it.

6. Complete the sentence:

The useState hook starts with an initial state, but…

  • the useReducer hook gets a reducer function in addition to the initial state. (CORRECT)
  • the useReducer hook cannot be used to track the state at all. 
  • the userReducer hook must be used when the initial state is an object. 

Correct: Correct. The useState hook starts with an initial state, but the useReducer hook gets a reducer function in addition to the initial state.

7. True or false: useRef is a custom hook in React.

  • Yes. 
  • No (CORRECT)

Correct: Correct. The useRef hook is a built-in hook, just like some other hooks are, such as the useState or useReducer.

8. JavaScript is a single-threaded language, meaning…

  • …you can use it with React only when this single thread is used with the useEffect hook. 
  • …you can use it with React only when this single thread is passed to the useState variable. 
  • …it can only do a single thing at any given time. (CORRECT)

Correct: Correct. This is a true statement.

9. Which statement is correct about the following code snippet:

import { useEffect } from "react";
 
function useConsoleLog(varName) {
  useEffect(() => {
    console.log(varName);
  });
}
 
export default useConsoleLog;
Choose the correct statement below.
  • This is an example of a custom hook. (CORRECT)
  • This code is an example of an implicit state-updating function. 
  • This code is an example of an explicit state-updating function. 

Correct: Correct. This is an example of a custom hook.

10. Find the error in this code:

import {useState} from "react";
 
export default function App() {
  const [restaurantName, setRestaurantName] = useState("Lemon");
 
  function updateRestaurantName() {
    useRestaurantName("Little Lemon");
  };
 
  return (
    <div>
      <h1>{restaurantName}</h1>
      <button onClick={updateRestaurantName}>
        Update restaurant name
      </button>
    </div>
  );
};
  • The onClick event should not be this: onClick={updateRestaurantName}
  • The state-setting function’s variable name in the array destructuring should not be setRestaurantName. 
  • The code inside the updateRestaurantName() function definition should not invoke useRestaurantName(“Little Lemon”) (CORRECT)

Correct: Correct. The code inside the updateRestaurantName() function should invoke setRestauranName(“Little Lemon”).

11. Which of the following is true about the useState hook? 
Select all that apply.   

  • The useState hook’s return value in React is the array data structure. (CORRECT)
  • The useState hook allows you to work with state in components. (CORRECT)
  • The useState hook invocation returns a two-member array. (CORRECT)
  • When using the useState hook, you must use the state-updating function to update state. (CORRECT) 

Correct: That’s correct. The invocation of the useState hook returns an array.  

Correct: That’s correct. The useState hook is used to work with state in a React component.  

Correct: That’s correct. When calling the useState() hook, the returned array holds the state variable’s value asthe first item of that array and the function that will be used to update the stateas the second item of that returned array.  

Correct: That’s correct. There is only one correct way to update state when using useState and that’s through the state-updating function. 

12. You can use an object with multiple properties as the initial value of the state variable.

  • True (CORRECT)
  • False

Correct: That’s correct! You can use an object with multiple properties as the initial value of the state variable, just like the formData state variable in the example, where the useState hook was invoked with the object containing two properties (the goal property and the by property).

13. True or False:

A pure function will perform a side effect.   

  • False (CORRECT)
  • True

Correct: That’s correct. While a pure function has no side effects, an impure function will perform a side effect.  

14. How should you add a side effect functionality In React?   

  • Using an arrow function  
  • Using a dependency array  
  • Using the useEffect hook  (CORRECT)

Correct: That’s correct. The correct way to add a side effect functionality is to use the useEffect function.  

15. Is this code using a valid invocation of a hook?

if (data !== '') { 
   useEffect( () => { 
    setData('test data') 
   }) 
}
  • Yes
  • No (CORRECT)

Correct: That’s correct. The useEffect hook has been used inside the If conditional statement, and that makes the use of the hook in this code invalid.

16. Which of the below statements is an accurate description of JavaScript utilizing the fetch function?

  • When JavaScript uses the fetch function it is delegating duties to an external API so that it can continue its process. This is known as single-threaded execution.   
  • When JavaScript uses the fetch function it is performing each step ofthe process one by one, carrying out all of the required duties. This is known as single-threaded execution.  
  • When JavaScript uses the fetch function it is performing each step ofthe process one by one, carrying out all of the required duties. This is known as asynchronous JavaScript.  
  • When JavaScript uses the fetch function it is delegating duties to an external API so that it can continue its process. This is known as asynchronous JavaScript. (CORRECT)

Correct: That’s correct. The fetch function utilizes external APIs to perform tasks that would be cumbersome for JavaScript to fulfil alone.  

17. Which of the statements below best describes how the fetchData function is working?   

  • The fetchData function is initially fetching data from the randomuser.me API, next it retrieves a response from the API in JSON format, and finally updates the state variable with the returned data.  (CORRECT)
  • The fetchData function is initially fetching data from the randomuser.me API, next it retrieves a response from the API in JSON format, and finally returns the user data as the output.
  • The fetchData function is initially fetching data from the randomuser.me API, next it retrieves a response from the API in text format, and finally updates the state variable with the returned data.

Correct: That’s correct. The fetchData function initially fetches data from the randomuser.me API, next it retrieves a response from the API in JSON format, and finally updates the state variable with the returned data.  

18. Which of the following statements is true about the useReducer hook?   

  • The useReducer hookStarts with an initial state only   
  • The useReducer hook starts with a reducer function only  
  • The useReducer hook starts with an initial state and reducer function (CORRECT)

Correct: That’s correct. The useReducer hook gets an initial state and a reducer function.  

19. What is the data type of the returned value from the useRef hook invocation?   

  • An object (CORRECT)
  • An array
  • A string
  • It can be any data type 

Correct: That’s correct! The returned value from the useRef hook invocation is an object.  

Interactive CSS CONCLUSION

Now that you’ve learned about the different types of hooks available in React, and how to put them to use within your application, it’s time to start building your own custom hooks.

This will allow you to really leverage the power of React and create some truly dynamic applications. So what are you waiting for? Get started today by enrolling in Coursera’s React course. You’ll be glad you did!

Subscribe to our site

Get new content delivered directly to your inbox.

Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!