React hooks are a relatively new addition to the library. One of these hooks, the useState hook, allows you to access state in a component while eliminating the need to use a class component.

This allows you to write less code, as you no longer have to inherit from React.Component, and you can write a simple JavaScript function. First, you’ll have to import the useState function from react.

import React, { useState } from React

The useState hook takes in a value, and it returns an array. The first index of that array contains the state value that you passed in, and the second index of that array contains a function used to update that state value. Updating state using this function causes the component to re-render, just like with using class hooks.

You can use destructuring to easily assign your state value and your update function to their own variables like so:

function LikeButton(){
const [likes, setLikes] = useState(0);

It is convention to name the ‘setter’ function set(variable name). We can now easily use this function to update our state and re-render our component!

function LikeButton(){
const [likes, setLikes] = useState(0);
<button onClick={() => setLikes(likes + 1)}>
Like Me!

Full-stack web developer with a background in the service industry, sound design, audio engineering, and theatre performance.