Using React State with Functional Components

Sarah Pfohman
2 min readNov 29, 2021

--

Photo by Tudor Baciu on Unsplash

With the update to React version 16.8.0 in February of 2019, the capability of using state within Functional components was added. State is a JavaScript object managed within functional components, similar to a variable declared within a regular function.

State should be used whenever you need to keep track of data or properties that might change or update between renderings. The change to state is what triggers the component to re-render or update.

State should be used within the component where it is needed. If that state is needed in multiple components, then the most recent ancestor to both components should be used. To use state within the functional component, it needs to be called or imported at the top of the component.

How to import useState

To initialize state, you create a destructured array, the initial value being the item to update, and the second value is the function to update or change that referenced value.

const [thingToTrack, setThingToTrack]=useState('initialValue')

State can take any value initially: a number, string, Boolean, object, or even a function. To update or change state, the setState function should be used.

Here’s a link to a few repl examples of how state can be used:

Button click to update state
Capture text and update state

These are just a few examples of how to update state. Here is a link to an excellent walk through example of how to build a React app and use state.

--

--

Sarah Pfohman

Software engineer, student, and true crime enthusiast. Check out my portfolio here: https://spfohman.github.io/