gubawhips
gubawhips

Reputation: 65

Using class property to set initial state in React

I have a React class component that with an initial state object in the constructor call. I originally just had an object literal assigned to this.state, but I need to share the initial state object with other methods in the class to reset the component. Is it ok/correct to move the initial state object to be a class property and reference that in the constructor?

class SampleComponent extends Component {
  constructor() {
    super();

    this.state = this.initialState;
  }

  initialState = {
    property1: "...",
    property2: "..."
  };
}

The code seems to work, but I'm not sure if this is the right way to go about this.

Upvotes: 2

Views: 679

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Decouple the initialState from the class:

const initialState = {
    property1: "...",
    property2: "..."
};

// As Class
class SampleComponent extends Component {
  state = initialState;
  ...
}

// Hooks
function SampleComponent(props) {
  const [myState, setMyState] = useState(initialState);
  ...
}

In this way, you avoid future bugs regarding this.initialState.

Upvotes: 5

Related Questions