flemadap
flemadap

Reputation: 689

React Hooks and the use of useState

I have a component with some states. What is the different between

Example 1:

function CompA() {
  [a, setA] = useState(0);
  [b, setB] = useState("Test");
  return (<div>{{ a }} and {{ b }}</div>);
}

and Example 2:

function CompA() {
  [state, setState] = useState({a: 0, b: "Test"});
  return (<div>{{ state.a }} and {{ state.b }}</div>);
}

Example 2 is more verbose. But all the hooks example I see on the internet prefer the Example 2's style. Is there any performance penalty or best practice that preferred one or another??

Upvotes: 0

Views: 119

Answers (1)

wentjun
wentjun

Reputation: 42516

Both approaches will end up with the same end goal, whereby you will create a component that renders the following element: <div>{{ state.a }} and {{ state.b }}</div>

However, here's a scenario for Example 1. If you wish to update both states(a, and b) , you will have to call 2 different methods to update the state:

setA(1);
setB('bbbb');

On the other hand, for Example 2, you will only need to call 1 method to update the state.

setState({
  a: 1,
  b: 'bbb',
});

However, the downside of this approach is that, you will have to spread the entire state object if you only wish to update only one of the properties (credit goes to @DrewReese for pointing this out). For instance, if you want to update only b,

setState({
  ...state, 
  b: 'bbb',
});

That being said, it will not be accurate to state that Example 1 is less "performant", as React will batch the updates if they are called within the same event handler, and cause a single re-render.

Upvotes: 4

Related Questions