FAQ: The State Hook - Why Use Hooks?

This community-built FAQ covers the “Why Use Hooks?” exercise from the lesson “The State Hook”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn React

FAQs on the exercise Why Use Hooks?

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I’ve never been so infuriated by an example before. “Don’t mind the details” just try to understand what the code is trying to do? Why not explain the details before putting it together and overwhelming the student? It’s asinine. Try to understand why multiple constants are being defined at the same time to an empty object or array? We have used prevProps, but now there are prevState and prev? Thankfully I’ve seen the spread syntax before but if I didn’t that’s another brand new concept. Shame on whoever designed this course. I am not going to be continuing with my subscription. This is horrible.

9 Likes

Can anyone tell me why we need to set a unique ID for every onChange event in the text input field.
Why not create a unique Id for the newTodo onSubmit and store it in AllTasks array.
(When creating a todo list in react)

What on earth is going on with the code snippet it wants you to look at?

Just dropping this bombshell on a Friday night…

  handleChange({ target }){
    const { name, value } = target;
    this.setState((prevState) => ({
      ...prevState,
      newTask: {
        ...prevState.newTask,
        [name]: value,
        id: Date.now()
      }
    }));

mind blown

I’ll comment as I think I understand what’s going on until I don’t…

handleChange({ target }){
    // destructure "name" and "value" from "target" - fine, I get that 
    const { name, value } = target;
    // setState and pass in the previous state, also fine
    this.setState((prevState) => ({
      // you set the current state to be the previous state's values???? Why?
      ...prevState,
      // next, overwrite the newTask value you've just set above
      newTask: {
        // Next you set newTask to a copy of the old newTask.  This keeps the title when you switch to description. fine
        ...prevState.newTask,
        // then use a computed property name to set the input.  fine (once i'd looked up what that was).
        [name]: value,
        // why would you keep regenerating a different id every key stroke?
        id: Date.now()
      }
    }));
  }

Why on line 7 above is the previous state used? I removed it from the editor and the code works exactly the same.

Hey @mrste, not entirely sure whats going on either (saw your comment on Friday night but thought i drop this on a Tuesday night).

I think this video about setState might help.

Instead of returning the old state as an object to setState, you pass in a function that takes prevState as an argument for setState. This way you can safely pass data from a previous state to a new state. This is useful, if state updates depend on asynchronous result (Ex: Clicking a button multiple times to get the current time in seconds). This was probably a bad example…oh well.

For your 4th comment this.setState((prevState) =>, they use object compostion. So setState will have access to 2 objects:

  1. An expanded object (…prevState): shorter syntax to list props of prevState (to iterate through maybe).
  2. A newTask object.

I guess name property of object target will store the name and id. Why is this done? I think the purpose of handleChange ({target}) is to store every update or change on a target object and those changes or updates can be accessed and/or modified via the name or id properties.

I wasted an hour writing this horrible attempt of an explanation :skull_and_crossbones: Incase I missed the point, hopefully the video I linked above as well as this article might help.

Cheers mate!

Thanks, @stoutfella that makes sense.

I carried on regardless and the later tutorials filled in the gaps. The last exercise has you write that code from scratch from what you’ve learned to make sure you understand it. I should’ve just got stuck in instead of moaning and getting hung up on it!

Cheers :+1:

2 Likes

Hey all, i had a question regarding the examples shown on this page: https://www.codecademy.com/courses/react-101/lessons/the-state-hook/exercises/why-use-hooks

Using the finished webapp, what i’ve noticed is that:

  1. if i very quickly click on the Add Task button after having typed something, nothing happens. (if i do it fast enough i can throw in 5 clicks before the button actually works)
  2. if i click on Details field while continuing to type in Add Task field, the focus never shifts. It only shifts after i’ve stopped typing & then a good second or so has passed.

I don’t like this lag. if user clicks on something, the cursor focus should immediately switch. Any ideas why does this delay happen? How do i prevent this delay?

It seems this example is using idiomatic JS, which is very important to teach us. Hence it’s a great disappointment to learn Codecademy never taught us this, even in the intermediate JS class (and no advanced class?). I’m sure you’ve figured this out, but for the next person, some references to understand what is happening

The JS spread operator (…variable):

handleChange is the React convention for the onchange (again, onChange for React) event handler. It gets passed an Event object, which has lots of properties as explained here:

So the idiom used:

handleChange({ target }){

is saying “use only the target property of Event as a the method parameter.”

Shame, they could have included all this in the comments, but this whole course seems hastily created.

In index.js, we have:

import App from “./Container/AppFunction”;

ReactDOM.render(
,
document.getElementById(“app”));

However, we are exporting AppClass or AppFunction in the other files. How does JavaScript know that App refers to AppClass or AppFunction?

Ah, answering my own question: default exports can be renamed on import. It’s called an “import alias”:

true, post must be at least 20 words so I must say what u say is true.

import React, { Component } from "react";
import React, { useState } from 'react';

In this lesson, I wonder why here import Component in this way? I used class App extends React.Component lots of time, but I never import Component. And I feel confused about why React doesn’t need {}, but Component needs. I thought React and Component are also in my node_modules, aren’t they? The same question is why I have to use {} to import useState?

I guess maybe I have to know more about module knowledge? I often modulize my projects and import componet.js. But I don’t know anything about node_modules.

import defaultExport, { namedExport } from 'react';

So React is the default export in react.js, and useState is the named export in react.js?
But why not import {useState} from ReactHooks.js?

I have a question about when we imported the other file into Index.html.

// import App from "./Container/AppClass";
import App from "./Container/AppFunction";

How are they both allowed to be called ‘App’ when:

  • AppClass’s class component is called AppClass
  • AppFunction’s function component is called AppFunction

Doesn’t the file name and component name need to match?

In AppClass.js, you will see

export default class AppClass extends Component {

Similarly, in AppFunction.js, you will see

export default function AppFunction() {

The use of default keyword means a default export is being done as opposed to a named export.

For detailed explanation see the documentation: export - JavaScript | MDN :

Every module can have two different types of export, named export and default export . You can have multiple named exports per module but only one default export.

Thank you!! I definitely think I had forgotten this - much appreciated for the clear explanation!

1 Like