Initial component state

The initial state of a component isn't actually required, but if your component uses state, it should be set. This is because if the component expects certain state properties to be there and they aren't, then the component will either fail or render something unexpected. Thankfully, it's easy to set the initial component state.

The initial state of a component should always be an object with one or more properties. For example, you might have a component that uses a single array as its state. This is fine, but just make sure that you set the initial array as a property of the state object. Don't use an array as the state. The reason for this is simple: consistency. Every React component uses a plain object as its state.

Let's turn our attention to some code now. Here's a component that sets an initial state object:

import React, { Component } from 'react';

export default class MyComponent extends Component {
// The initial state is set as a simple property
// of the component instance.
state = {
first: false,
second: true
};

render() {
// Gets the "first" and "second" state properties
// into constants, making our JSX less verbose.
const { first, second } = this.state;

// The returned JSX uses the "first" and "second"
// state properties as the "disabled" property
// value for their respective buttons.
return (
<main>
<section>
<button disabled={first}>First</button>
</section>
<section>
<button disabled={second}>Second</button>
</section>
</main>
);
}
}

If you look at the JSX that's returned by render(), you can actually see the state values that this component depends on—first and second. Since you've set these properties up in the initial state, you're safe to render the component, and there won't be any surprises. For example, you could render this component only once, and it would render as expected, thanks to the initial state:

import React from 'react';
import { render } from 'react-dom';

import MyComponent from './MyComponent';

// "MyComponent" has an initial state, nothing is passed
// as a property when it's rendered.
render(<MyComponent />, document.getElementById('root'));

Here's what the rendered output looks like:

Setting the initial state isn't very exciting, but it's important nonetheless. Let's make the component re-render itself when the state is changed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.81.240