DEV Community

Austin Brown
Austin Brown

Posted on

React: Using State in Functional Components

Traditionally in React JS, an app would be set up in such a way that there is a main stateful class component which holds all of the state values and methods to set them with, and these values or methods would be passed to its functional children components as props. As of React version 16.8, Hooks can be used to use stateful variables directly within a functional component.

The reason it may be useful to do this is if the state values that you need to set do not need to be accessed by or do not affect any other component in the app—such as a counter of some kind or an array that holds the views for a particular component. This also can help with keeping your main App.jsx file free from being cluttered.

useState()

Getting started with this feature is extremely simple:

import React, { useState } from 'react';
function Example() {
   const [index, setIndex] = useState(0);

...

The above example demonstrates the useState() React hook. In the first line, useState needs to first be imported from the react object. The index and setIndex variables shown can be any name that you would like them to be. The first variable (in this case, index), will always be the actual current value of your state variable, and the second (typically named 'set' and then the name of the variable listed just before it) is a function used for setting said variable—just like the traditional setState() with class components. And finally, the 0 seen in the parenthesis after useState() is the initial value before anything has been set. This can be set to any data type you would like.

So inside the Example component, if you wanted to do something like increment this new index variable, it might look something like this:

setIndex(index + 1);

useEffect()

The equivalent from a traditional class component to explain useEffect() would be the componentDidMount() and componentDidUpdate(). It acts as sort of a combination of the two.

Here is an example:

useEffect(() => {
      axios.get('/api/messages')
      .then(response => {
         setMessages(response.data)
      })
      .catch(err => console.error(err));
   }, []);

Using useEffect() as shown above is the componentDidMount() equivalent. The first argument in useEffect() is the function to be called after the initial render, but the main thing to note here is the second argument passed at the end—the empty array literal. When it is left empty, the function will only ever be called after the initial render. Adding state variables to it (separated by commas) will cause the useState() instance to act more like componentDidUpdate(). This function will now also be called any time a change happens to the specified variables. And that's it!

Conclusion

These hooks are just a couple of basic ones to get started with, but alone they can completely change the way your app is structured and really simplify/cut down on a lot of your code. Additionally, no other changes need to be made to an existing React app to use these hooks other than the basic importing of the 'useState' and 'useEffect' variables, and they are one hundred percent compatible to work side by side with and inside of traditional class components as well. More information about these hooks can be found in React docs here: https://reactjs.org/docs/hooks-intro.html

Top comments (6)

Collapse
 
tiagojpdias profile image
Tiago Dias

Be careful about that code snippet regarding useState update function.

// index is 10
...
setIndex(index + 1) // next iteration index = 11
(...)
setIndex(index + 1) // next iteration index = 11
Enter fullscreen mode Exit fullscreen mode

But if you read the documentation about functional updates then you'll have to use a callback to grab the latest value.

This is important whenever you're updating a state using the previous state for calculations.

// index is 10
...
setIndex((index) => index + 1) // next iteration index = 11
(...)
setIndex((index) => index + 1) // next iteration index = 12
Enter fullscreen mode Exit fullscreen mode
Collapse
 
austinbrownopspark profile image
Austin Brown • Edited

Thanks! I actually have seen it both ways and was confused about why they both work so that is really helpful

Collapse
 
xlpacman805 profile image
Johnny Meza

Awesome! Thanks for writing something simple and concise. I've been wanting to learn how to use state in functional components but haven't had time to really experiment, so I'll just use the normal ES6 classes. But this helped get a good grasp of how to think about State in functional components, Thanks!

Collapse
 
codingknite profile image
Joel P. Mugalu

Great article Austin. How do you write your code snippets with multiple colors?

Collapse
 
austinbrownopspark profile image
Austin Brown • Edited

Thanks! And it's super simple, just 3 backticks immediately followed by the word javascript on a single line before your code and then 3 more backticks on a single line after the code and then the colors happen automatically

Collapse
 
codingknite profile image
Joel P. Mugalu

Thanks 😁 I just in cooperated it in my article. Looks way better