2

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response. Totally makes sense to just move that object outside of the class. 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.