react-hooks-revisited.jpg

Photo by Etienne Girardet on Unsplash


Intro

Some time ago, before React Hooks were officially released, I have written another article about them. It was an attempt to learn and explain this new feature. Now, when they are officially part of the last React releases, I have decided to revisit them and try to present better examples of their usage.

Why

Right after my first presentation, I've received some very useful comments by a colleague of mine. Comments regarding the presentation and the examples, and advice of how I can do better. I kept these comments in my email for some time. And today I will try to follow them, so we can get better understanding about this feature, which now can be used in any new or existing project.


Show Time

Since we have covered the theory behind the hooks last time (and there are a lot of nice explanations on the subject out there now), I don't plan to repeat it here. What I plan is to start directly with examples, but to strive to keep them as clear and focused as possible. 🐽

Example 1:

In this example we will take a closer look at the two of the most important built-in hooks - useState and useEffect.

📌 State Hook - useState()

📚 Theory - this is just to remind us what is this hook meant to be used for and then we will see how to use it below. What React documentation say is: "one of the Hooks provided by React is called useState. We're also sometimes going to refer to it as the "State Hook". It lets us add local state to React function components". This means that whenever we need to manipulate our component state, we can go for useState hook.

👉 Practice - you can see live example here and play with it.

📌 Effect Hook - useEffect()

📚 Theory - this is just to remind us what is this hook meant to be used for and then we will see how to use it below. What React documentation say is: "The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects". This means that whenever we need to perform some side effect or use a result returned from such, we should go for useEffect hook.

Here is an example in which we will see what are the differences when we use this hook with one parameter and with two parameters. We also will see what happens if we provide a return value for the first param.

👉 Practice - you can see live example here and play with it.

If you want to go really deeper into this, here Dan Abramov posted A Complete Guide to useEffect. It's a really long article, but it's worth it.