React classes setState vs Hooks (useState)

Hello all,

am doing a second course on udemy. The first was a web developer bootcamp (by Angela Yu) where she introduced in her react part hooks. I understood it quite well.
Now I am doing a React and Redux course (by Stephen Grider), where he explains classes and setState which I fail to understand (because of the “this” word).
But what I would like to know, is, which approach is the used one? Or are both used case dependent?

Found an article on medium about my question, but I still fail to understand it.

Thanks in advance!

I just learned about hooks yesterday watching the Beginner’s Guide to React w/ Hooks (2020) Free Course by Colt Steele on YouTube. He was basically suggesting that new projects will be moving to functions. The folks behind React seem to agree in their docs in the Gradual Adoption Strategy section.

1 Like

Functions components could not have state, so hooks were added to the language. Prior to that, the API used classes. So all of the material online that is > 2 years old will be using the class API because hooks did not exist. They do the same thing. Hooks generally describe how React is actually doing things a bit better than classes

I would probably take a refresher on how OO works in JS. this isn’t a React thing, it’s a fundamental concept in JavaScript.

A class is a template for creating an object. This class creates an object with a property state. setState and render are functions attached to the prototype of that object. this is the calling context. When it gets created, this will refer to the object itself [when you are inside the object].

It is hard for people to understand. It tends to be confusing for beginners, and it also doesn’t work like it does in other languages, so it tends to throw experienced devs who are coming to JavaScript from other languages.

1 Like