Chapter 11: Migrating from React Class Components

  1. How are React class components defined?
    • React class components are defined by using class ComponentName extends React.Component {
  2. What do we need to call when using a constructor with class components? Why?
    • We first need to call super(props) to ensure that the props get passed on to the React.Component class
  3. How do we set the initial state with class components?
    • We can set the initial state in class components by defining the this.state object in the constructor
  1. How do we change the state with class components?
    • In class components, we use this.setState() to change the state
  2. Why do we need to re-bind the this context with class component methods?
    • When passing a method to an element as event handler, the this context changes to the element that triggered the event. We need to re-bind the this context to the class to prevent this from happening.
  3. How can we re-bind the this context?
    • We need to use .bind(this) on the method in the constructor. For example, this.handleInput = this.handleInput.bind(this).
  4. How can we use React context with class components?
    • We can set the contextType and then access this.context. For example, static contextType = StateContext.
    • If we want to use multiple contexts, we can use context consumers. For example, <StateContext.Consumer>{value => <div>State is: {value}</div>}</StateContext.Consumer>.
  5. What can we replace state management with when migrating to Hooks?
    • We can replace this.state and this.setState with a State Hook
  1. What are the trade-offs of using Hooks versus class components?
    • Function components with Hooks are simpler (no need to deal with constructors, this, or destructuring the same values multiple times, no magic when dealing with contexts, props, and state, no need to define both componentDidMount and componentDidUpdate). Function components also encourage making small and simple components, are easier to refactor and test, require less code, are easier to understand for beginners, and are more declarative.
    • However, class components can be fine when sticking to certain conventions and using the latest JavaScript features to avoid this re-binding. Furthermore, class components might be easier to understand for the team, because of existing knowledge.
  2. When and how should an existing project be migrated to Hooks?
    • Slowly replace old class components with Hook-based function components when appropriate. For example, when you are already refactoring a component.
..................Content has been hidden....................

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