React Hooks — useState

Maria Le
Oct 17, 2020

--

We can use state in functional components!

With the implementation of hooks, React allows us to use state without a class. We can use state in a functional component with the useState hook instead of using class components every time we need to use state.

What is a Hook?

According to the React docs a hook is a special function that lets you “hook into” React features.
Below I will give an example of a LikeButton component using the useState hook:

Example

code snippet example of useState hook for a LikeButton functional component

In this example snippet, we are destructuring what the useState hook is returning.

You can think of our first destructured variable numOfLikes as “this.state” and our setCount function variable as “this.setState” like we would use in class components to reference state. The argument passed into useState(0) is setting our initial state of numOfLikes to 0.

When our LikeButton component is rendered, state will be updated every time a user clicks the button! Very clean and cool! This is just a taste of what hooks can do.

You can read more about the cool features and implementation of what Hooks give us as React developers in the official React Hooks documentation.

Happy coding!
Mars

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Maria Le
Maria Le

No responses yet

Write a response