• Chris Manciero

Accessing State with React Hooks

Updated: Jan 7, 2019

A new feature of React that is getting developers excited are Hooks. Hooks provide the functionality to use state and other React features in a React functional component. Probably the most exciting part of using Hooks is the ability to add React state to your functional components. This post will discuss how to use the useState hook to set and get state values in your functional component.


Before you can start using the useState Hook you will need to import useState into your component.

import React, { useState } from "react";

Now when you want to add state functionality use the following syntax:

const [searchTerm, setSearchTerm] = useState('');

Another way to look at the above code would be:


You may be asking yourself, what is this code doing? Let me break it down for you. Using array destructuring we are able to assign the state property to use in the component as well as the function method to use for setting the variable. The second part useState('') is setting the initial state value.

Reading State

If you want to access the state value, just use the value for VARIABLE_NAME.

const [searchTerm, setSearchTerm] = useState('');<p>You search for: {searchTerm}</p>

Updating State

To update the state value use the METHOD_TO_UPDATE function.


Multiple state variables

If you are looking to use more than one state variable in your function component, you just need to declare each state individually.

const [searchResults, setSearchResults] = useState([]);const [searchTerm, setSearchTerm] = useState("");

Code example

Here is a sample application I made that uses the useState hook.

36 views0 comments

Recent Posts

See All