221203 3rd TIL - Props, State, React re-rendering

hannah·2022년 12월 4일


While props and state both hold information relating to the component, they are used differently and should be kept separate.

Props

function Welcome(props) {
  return <h1>Hello {props.name}</h1>;
}

props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable as far as the Component receiving them is concerned. During a component’s life cycle props should not change.

A Component cannot change its props, but it is responsible for putting together the props of its child Components.

A component can also have default props, so if a prop isn’t passed through it can still be set.

We can make the name property optional by adding defaultProps to the Welcome class:

class Welcome extends React.Component {
  render() {
    return <h1>Hello {this.props.name}</h1>;
  }
}

Welcome.defaultProps = {
  name: "world",
};

State

When a component needs to keep track of information between renderings the component itself can create, update, and use state.

The state starts with a default value when a Component mounts and then suffers from mutations in time (mostly generated from user events). It's a serializable* representation of one point in time—a snapshot.

A Component manages its own state internally, but—besides setting an initial state—has no business fiddling with the state of its children. You could say the state is private.


(https://lucybain.com/blog/2016/react-state-vs-pros/)

React Re-rendering

Every re-render in React starts with a state change. It's the only “trigger” in React for a component to re-render.

Now, that probably doesn't sound right... after all, don't components re-render when their props change? What about context??

Here's the thing: when a component re-renders, it also re-renders all of its descendants.

  • Big Misconception #1: The entire app re-renders whenever a state variable changes.
    - NO. Because data can't flow "up" in a React application, we know that this state change can't possibly affect <App />. And so we don't need to re-render that component.

  • Big Misconception #2: A component will re-render because its props change.
    - NO. Props have nothing to do with re-renders. When a component re-renders, because one of its state variables has been updated, that re-render will cascade all the way down the tree, in order for React to fill in the details of this new sketch, to capture a new snapshot. When a component re-renders, it tries to re-render all descendants, regardless of whether they're being passed a particular state variable through props or not. However, you can ignore certain re-render requests by using memoization (React.memo).

(https://www.joshwcomeau.com/react/why-react-re-renders/#the-core-react-loop)

profile
aspiring frontend developer based in NYC

0개의 댓글