Grateful
Grateful

Reputation: 10175

React.js state object vs useState hook?

I started React by learning about the useState hook to manage component states. However, I have recently discovered that it is possible to use a state object instead. I'm confused, and can't seem to find many references on the internet to help me understand the difference.

What are the differences, if any between the following... And which one is preferred, if at all?

Option 1: State object:

class User extends React.component {

  state = {
    username: 'Tyler'
  }

Option 2: useState hook:

class User extends React.component {

  const [state, setState] = useState({
        username: 'Tyler'
  })

Upvotes: 0

Views: 2809

Answers (2)

Edwin Clement
Edwin Clement

Reputation: 565

So, there is a bit of misunderstanding here.

State Object, or this.state was used when React used classes.

This approach had some downsides. React needed to add a lot stuff to the object(when class is initialized) to make it compatible to react.

Hence since React 16 or so, it added the ability to using functions as building blocks for the application. The older approach(using classes) stil works, but not encouraged. Classes does have some additional functionality as of this moment (https://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes). Error Boundary (https://reactjs.org/docs/error-boundaries.html) is one such thing.

Before 16, functions could be used as components, but didn't have state. With Hooks, the functions could have state as well.

This does come with some restrictions and how-tos in regards to usage(https://reactjs.org/docs/hooks-rules.html)

The best resource on hooks is the docs from react on the subject.

The last, probably most important pro is that the code is cleaner.

P.S. the second example won't work, useState has to be within a function defn.

// Option 2: useState 
function User() {
  const [state, setState] = useState({
    username: 'Tyler'
  })
}

Upvotes: 3

Or Assayag
Or Assayag

Reputation: 6336

useState is part of a whole new concept in React (16.8+), that's called hooks. Hooks are a more efficient and simple way to write in React.

Hooks solve pain points:

  1. Managing State: Reusing logic between multiple components can lead to wrapper hell or deeply nested components.

  2. Side Effects: Unrelated mixed in logic in lifecycle methods can get repetitive, and cause unnecessary side effects.

  3. Optimization: Hooks might reduce your bundle size.

Please read all in here: https://medium.com/better-programming/react-hooks-vs-classes-add2676a32f2

Upvotes: 2

Related Questions