React hooks

Nausheen Akhter
2 min readAug 23, 2022

--

This is a topic I’ve needed to review many times to try to understand. I’m doing a course on Udemy called React with Hooks for Beginners right now to learn it systematically. I might have to break down my learning into a few posts.

What are React hooks?

According to the article “React Hooks,” “Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which ‘hook into’ React state and lifecycle features from function components. It does not work inside classes.” I like this definition more than the one in the course.

When can you use hooks?

Let’s look at the article once more. It states, “If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.” I’ll go back to the course to walk through the useState hook.

useState() Hook

This hook “is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state,” according to the article. I like the example of a counter in the course and I’ll review it here. (Images are currently not uploading so I will publish the article as text-only and update when able to upload images again.)

First, I created Counter.js file within src/components. We set up a functional component and export default. Then, I imported it into App.js to render.

Then I finished setting up the counter with the handleButtonClick function.

Next, I imported the useState hook from the React library.

Before the handleButtonClick() function, I created a variable const and within a de-structured array, I gave the state variable name “clicks” and then the function that updates the state variable called “setClicks.” This entire const is set equal to useState and in parentheses, I set the initial value of the state variable (clicks) to zero.

Then, with the handleButtonClick() function, I defined the setClicks function to clicks+1. This means that when the button is clicked, the state will be updated by counting up 1.

I updated the rendering to dynamically render the current clicks using {clicks} and finally set the entire contents of the render function within fragments to render both the button and the counter.

--

--

No responses yet