Search code examples
javascriptreactjsreact-hooksuse-state

Is useState meant to hold a custom object?


const [obj, set_obj] = useState(new CusObj())

Is there any difference between useState holding a primitive vs a custom object?


Solution

  • From the docs

    Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

    setState(prevState => {   
      // Object.assign would also work
      return {...prevState, ...updatedValues};
    });
    

    Another option is useReducer, which is more suited for managing state objects that contain multiple sub-values.

    For complex state values I would go with the useReducer hook instead, but in short yes you can.