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.
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 statesstates.stateOne;// this is how we now update a statessetStates({...states,["stateOne"]:"newValue"});
Personally I prefer the simplicity of the first approach.
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:
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).
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.
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.
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.
Personally I prefer the simplicity of the first approach.
Thanks for the explanation. Yes, The first approach seems a lot more readable. Simplicity over everything else! 😃
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:
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?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).