Lesson 3: State Management Flashcards
When is it appropriate to use a Stateless Functional Component?
If a component is only using a render method to display content, then it can be converted into a Stateless Functional Component.
If the <ingredientlist></ingredientlist> Component in the following code is a Stateless Functional Component, how would you access the items prop inside the Component?
<ingredientlist></ingredientlist>
props.items
Stateless Functional Components do away with the thiskeyword.
How would you refactor the following code as a Stateless Functional Component?
class Email extends React.Component {
render() {
return (
{this.props.text}
);
}
}
const Email = (props) => (
{props.text}
);
Why do you never change state by writing this.state.whatever = so_and_so; and what substitute does React offer us?
You never want to change state manually using this.state because then React will not know what the previous state was. It’s overwriting it.
React gives us setState() to update state. Using the functional setState gives us access to the previous state.
What’s the difference between the functional and object setState methods?
Object is simpler and easier to read, but functional gives us access to the previous state.
Which is true about setting state in components?
- Whenever setState() is called, the component also calls render() with the new state
- State updates can be merged by passing in an object to setState()
- Updating state directly is ideal when you want to re-render a component (i.e., preferring this.state.message = ‘Hi there’; rather than this.setState({ message: ‘Hi there’ });
- State updates can be asynchronous (i.e., setState() can accept a function with the previous state as its first argument)
- setState() should be called within the component’s render() method
1, 2, and 4 are true.
At the end of the day, your UI is just a function of your state. Being able to leverage React’s automatic re-renders when resetting state can give your app’s users a truly dynamic experience.