Setting an object in React Hook

Viewed 717

Is there any differences setting an object in React Hook by using these two approaches?

const INITIAL_STATE = {
    foo = '',
    bar = ''
}

// ...

// Method 1
const [state, setState] = useState(INITIAL_STATE);

// Method 2
const [state, setState] = useState({ ...INITIAL_STATE });

Both method works fine, I just want to know if there are any fallbacks or advantages of using one over the other.

3 Answers

useState will use initial state only on the first call. But it will be called on every render and { ...INITIAL_STATE } will create a new unused object every time. This overhead should be unnoticeable.

First the init object should be written as the following, using the colon instead of equal sign.

const INITIAL_STATE = {
    foo : '',
    bar : ''
}

while using Method 1, the hook will reference INITIAL_STATE, which means, any changes made to this INITIAL_STATE will also affect the state.

for example, create a button and give it a onClick function to update the value for INITIAL_STATE.foo, will also affect the state.foo, if you console.log(state.foo), you can see the value has been updated.

Method 2, on the other hand, it will not reference the original object, but create a new object every time the hook function has been called, however, this deconstruct behavior only do a shallow copy, if the INITIAL_STATE has an attribute with a value of any object or array, it will also reference that object when you do a change to INITIAL_STATE.


function changeInitialState(){

  const INITIAL_STATE = {
     foo: '',
     bar: '',
     something: {
       name: 0
     }
  }

 const [state, setState] = useState({...INITIAL_STATE})

 return <button onClick={() => {
     INITIAL_STATE.something.name = 'hello';
     console.log(state.something.name) // you will see the name has been updated as well
  }}></button>

}

Method 1 passes in the initial object which means that the hook will always be using a reference to that original object.

Method 2 is creating a new object by spreading the original into a new one, meaning that the hook will no longer reference the original object.

Related