DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on

React Hooks: useState()

In a recent post on React hooks, I advocated their usage and explained how they could make your functional components flexible, extendable, and reusable. I would like to bring your attention to one of my favorite hooks: useState().

In some cases, you need to bring some state logic into a function component. Instead of rewriting it as a class component, you can hook into React state and lifecycle features. Implementing it is easy!

import React from 'react';
import {useState} from 'react'

function App() {

  const [importantThing, setImportantThing] = useState('initial value')

  return (
    <div >
      {importantThing}
    </div>
  );
}

export default App;

After importing useState from React, we see two values in an array being declared, and an initial value being set. The array is there to destructure the variables in useState, where the first value references the variable that lives in the state, and the second value is the reference to the function that changes the variable.

You can also set the variable to be an object, like so:

const [fruits, setFruits] = useState([{ apple: 'Granny Smith' }]);

Top comments (2)

Collapse
 
anastawfik profile image
Anas Tawfik

Important note that using an object as state in hooks doesn't behave the same as Class setState,
in Class's setState you can pass only rhe updated object attributes and it will be merged with the current state, meanwhile in Hooks it will replace the whole object so you need to handle the merging yourself, like:
setFruits({...fruits, banana: 'minions'})

Collapse
 
michaeljota profile image
Michael De Abreu

In this case, as same as arrays, it would be better to use the function callback and use the state that the callback gets as a param.