State and Lifecycle Flashcards
Where do you initialize state?
In the class constructor.
constructor(props) { super(props); this.state = {date: new Date()}; }
True/False: Class components should always call the base constructor with props?
Example:
constructor(props) { super(props); this.state = {date: new Date()}; }
True!
This is done because if we want to use this in the constructor, we need to pass it to super.
When is a component considered to have been mounted/unmounted?
Mounted – whenever the component is rendered to the DOM for the first time. This is called “mounting” in React.
Unmounted – whenever the DOM produced by the component is removed. This is called “unmounting” in React.
What are methods like ComponentDidMount()
and ComponentDidUnmount()
called in React?
These methods are called “lifecycle methods”.
Should you modify state directly?
Example:
this.state.comment = 'Hello';
No.
Doing so will not re-render a component.
What is the correct way to set state?
Use setState()
.
// Wrong this.state.comment = 'Hello'; // Correct this.setState({comment: 'Hello'});
Are state updates asynchronous?
You should assume yes. React may batch multiple setState()
calls into a single update for performance.
Why can we not rely on the values below for calculating the next state of counter
and how can we fix it?
this.setState({ counter: this.state.counter + this.props.increment, });
Why? Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
How? Use a second form of setState()
that accepts a function rather than an object.
// Correct this.setState((state, props) =\> ({ counter: state.counter + props.increment }));
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
True/False: When you call setState()
, React merges the object you provide into the current state.
True. For example, your state may contain several independent variables:
constructor(props) { super(props); this.state = { posts: [], comments: [] }; }
Then you can update them independently with separate setState()
calls:
componentDidMount() { fetchPosts().then(response =\> { this.setState({ posts: response.posts }); }); fetchComments().then(response =\> { this.setState({ comments: response.comments }); }); }
The merging is shallow, so this.setState({comments})
leaves this.state.posts
intact, but completely replaces this.state.comments
.
Is state accessible to any component other than the one that owns and sets it?
No. State is often called local or encapsulated.
What is a “top-down” or “unidirectional” data flow?
Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.