Introduction to React Hooks and Using Them in Your React App

Photo by Grace To on Unsplash

Welcome back, I’m glad you’re here! Today, I’m going to go over React Hooks because I’ve been working with them on my current project and I think they’re extremely useful. I’m going to do a quick walk-through that will hopefully get you on your way to using them in your next React App! I will be going over the purpose of hooks and why they’re so useful. Then, I will show you how to implement Hooks in your React App and guide you with an example. Let’s get started!

Introduction to React Hooks

Benefits of React Hooks

Two Rules of React Hooks

How Do We Implement React Hooks?

useState()

Example of useState() in action

The first thing that we need to do in the component is make sure to import the useState() hook from React (see line 1). Now, as you can see above, I am able to use a function instead of creating a class for the App component. On line 5, you will see the syntax used to establish a state object, age. The second variable, setAge, functions the same as setState() when we use classes, and allows you to change the state object, age. The parameter within useState() is the default/initial value of the state object. Then you can see on line 7 that the setAge function is used to change the value for the age variable every time the button is clicked. You can see how it looks like on the browser below.

Browser view of code above

You can see in the browser that every time a user presses the button, the age, which is displayed as well, will increase by 1.

Conclusion