DEV Community

loading...

Discussion on: React: Using the State Hook

Collapse
iyashsoni profile image
Yash Soni

Hey @link2twenty , nice article. One quick doubt though, How to initialise multiple state values?
A component may require more states, like we have seen in case of Class components.

Collapse
link2twenty profile image
Andrew Bone Author • Edited

That's a very good question and there are two ways to have multiple state values.

This way will create multiple variables and functions that can all be called, it generally the way React suggest doing it.

const [stateOne, setStateOne] = React.useState('one');
const [stateTwo, setStateTwo] = React.useState('two');

The other way is to have one state that is an object, this makes setting the state a little different as I'll show you.

const [states, setStates] = React.useState({
  stateOne: "one",
  stateTwo: "two"
});

// this is how we now read a states
states.stateOne;

// this is how we now update a states
setStates({...states, ["stateOne"]: "newValue"});

Personally I prefer the simplicity of the first approach.

Collapse
iyashsoni profile image
Yash Soni

Thanks for the explanation. Yes, The first approach seems a lot more readable. Simplicity over everything else! 😃

Collapse
iyashsoni profile image
Yash Soni

Hey @link2twenty , a follow-up question, if we do go ahead with the first approach that you just showed, won't it have a performance impact? Consider the following:

const [quote, setQuote] = React.useState("");
const [author, setAuthor] = React.useState("");

Now if we get a fresh quote in useEffect(...) and I update both quote and author on success, won't it cause 2 re-renders due to 2 set states?

Thread Thread
link2twenty profile image
Andrew Bone Author

Funnily enough, I was actually looking into this last night. I'd read a few places that several sets together sort of roll into one to save rendering lots. So I've made this quick proof of concept.

The number will go up each time we run render (based on either of those states changing).