5 minute challenge with React Hooks – For beginners

Tram Ho

Hello everyone, this article will be my own challenge in understanding React Hooks. Try it for 5 minutes and you’ll find out about React Hooks.

The first will be useState , one of the popular hooks in React Hooks.

1. useState

Let’s start with a functional component

As you can see, there is nothing new here. I just displayed 1 text and 1 button.

Now let’s import useState , to learn how to manage state in functional component.

Since these hooks are a function, try console.log see how it looks.

Yes, this is the result I got, an array

Try passing an argument to useState

The result is an array with the first element as the argument we passed above

Now, in the component , I can access the state in the value [0] and display it in <h1> instead of hardcoded.

Try to write briefly using array destructuring (it is similar to object destructuring, see my example below)

Results after using array destructuring in useState () hooks.

So I initialized the state first. The next question is how to change state value with hooks?

Remember that the useState () hook returns an array with 2 inputs. The second input is a function it uses to update the state value.

Of course, you can name it whatever you want, but by convention it is usually called with the “set-” prefix, and then any variable name you want to update.

It is very simple to use this function. Just call it and pass in the new value you want that state to! Or, like this.setState in a component class, you can pass a function that takes the old state and returns a new state. Rule of thumb: do this any time you need to rely on the state in the past to determine new state.

Try passing it on the onClick with the function setCount .

Write it down a bit:

Try running up to see the results, everyone. Okay, so that’s it for the first hooks, next I will look into useEffect .

2. useEffect

If I had to know all the lifecycle methods before, with useEffect hooks simplified the situation.

The import method is similar with useState

To useEffect to do something, pass it an anonymous function. Whenever React re-render component, it will run the function that we passed in useEffect .

This is all the code so far.

Share the news now

Source : Viblo