FAQ: The Effect Hook - Rules of Hooks

This community-built FAQ covers the “Rules of Hooks” exercise from the lesson “The Effect Hook”.

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

Learn React

FAQs on the exercise Rules of 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 #get-help.

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

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

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 #community:Codecademy-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!

This exercise is misleading. You can follow the steps as written and pass the checkpoints, but the code will not render anything to the preview.
After comparing with the solution, line by line, I found you need to set the initial state for items to an empty object. This is not mentioned anywhere in the instructions. The instructions only say about setting initial state for categories and selectedCategories. This caused a lot of frustration searching for a mistake that was never there - just simply poor instructions.

const [items, setItems] = useState({});
4 Likes

This lesson says that hooks should not be written inside nested functions but in the previous exercise we used stateSetter() inside the useEffect(). So is it good practice to write like this?

I understood that you can only use useState() on a top level, but once you called it, it’s okay to use part of what it returns , a.k.a. setState() inside of useEffect().

But I may be wrong.

2 Likes

yes, you are right, useState() is the hook so you need to use it on the top, but setState() isn’t a hook so you can use it anywhere except in the return cause it will cause an infinite loop in this case.

2 Likes

Made it through the first 55% of the full-stack course and enjoyed it. The hooks instructions have been difficult to understand for me though. I’ll get lost and then review the solution. Once I know the answer I try to implement the same thing, but still get a failed checkpoint. I’ve even gone so far as trying to copy and paste the solution and it rejects it whenever I input it. I’m confused as to what the instructions are looking for at this point. Specifically having difficulty with step 1 vagueness on Rules of Hooks

Perhaps you can copy/paste the code you are trying OR post a screenshot. That might offer a clue as to why you can’t progress. It may also offer clues as to what is causing you confusion.

I had the same problem with the first step. In the beginning, I couldn’t solve it even if I clone the code from the solution. The only way I managed to solve it at first was by replacing my code with the solution. After that, I reset the code and tried to copy/paste just the part that was related to the first step and it works as well. After that reset again, and type it by myself and it works again. I reset and reload the page many times after that and I got different results every time.

Here it doesn’t work

Here is a comparison with the solution code

Here the same code is working

1 Like

Thanks for proving it with the screenshots. I knew I wasn’t completely crazy!

For the Shop.js exercies. Do we need to add both [items, selectedCategory] to the dependency array for Effect Hook instead of just [selectedCategory].

Reasons:

  • First only the change in selectedCategory can trigger this hook and fetch new data from server?
  • setItems is called within in effect hook? So, doesn’t the setItem triggers the same effect hook again?

Can someone help me on this?

1 Like

The code does not get accepted on task two even if I copy the solution. I can not proceed with the course.

Also, I would like to say the the Hooks part of this course has been explained in a really shoddy way. I had to go to the official React docs just to understand what the exercises were asking me to do.

@prakashprajapati9544 I think you are correct. Including items in the dependency array for the existing code doesn’t seem necessary. If we change the selected category, it triggers the hook and fetches data. Using setItems, we update the items object with our fetched data. Since, items has changed, it triggers another useEffect. Fortunately, the additional call doesn’t incur much cost because we fail the if condition and exit the useEffect immediately. But, you are correct including items in the dependency array doesn’t make much sense. If something else was happening in the code, such as an option for resetting the items, then perhaps including items in the dependency array would be useful.

@ashyforthewin Perhaps just try copy pasting the code necessary for the second step. Step 3 involves uncommenting some code, so perhaps leave that part commented while you are trying to clear step 2.

Hi, does anyone have a fix for this error. I am getting the same grey cross even though my solution matches the Solution step 2 exactly.

What does the error message at the bottom say?
I myself didn’t run into any issues with this exercise (am using firefox). But a number of people in the thread have reported issues with the exercise. @aleksandarivezic9720 earlier in the thread has mentioned the manner in which he was able to clear the exercise. Perhaps that may help you complete the exercise.

I am having trouble understanding this particular line of code:

!items[selectedCategory]

What is it checking for ?
from:

useEffect(() => {

if (selectedCategory && !items[selectedCategory]) {

  get(`/items?category=${selectedCategory}`).then((response) => {

    setItems((prev) => ({ ...prev, [selectedCategory]: response.data }));

  });

}

}, [items, selectedCategory]);

If we look at the useState initialization
const [items, setItems] = useState({});
we see that items is an empty object.

The if condition is checking whether A) a category has been selected and B) whether that category has some sort of value assigned to it in our items object.

Suppose we click the ‘Shirts’ category button. Since a new category has been selected by us, this will trigger the useEffect you posted (because of the dependency array for the effect). The items object is empty at the moment and doesn’t have any entry for Shirts. So, the second condition !items[selectedCategory] will evaluate to TRUE. We will fetch the data and use setItems to update items to
{Shirts: ["T-Shirts", "Casual", "Formal"]}

If we click the ‘Pants’ button, the same as above happens and our items object will be updated to

{Shirts: ["T-Shirts", "Casual", "Formal"], 
Pants: ["Long Pants", "Sweat Pants", "Shorts", "Swimwear"]}

Now, let us click the ‘Shirts’ button again. Since we had earlier clicked on the ‘Pants’ button and have now changed the category to ‘Shirts’, so the useEffect will be triggered because of the dependency array. But, as soon as we encounter the if condition in the useEffect, this time !items[selectedCategory] will evaluate to FALSE. This is because the Shirts property in our items object already has a value assigned to it. So, our if condition will fail and we will exit the useEffect without doing anything. If we didn’t have the condition mentioned by you, then we would fetch data every time we changed category.