props in React

권민재·2023년 11월 26일
0

React

목록 보기
1/1
post-thumbnail

What is props?

React components accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

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

So props able parent components to deliver data to child components.

function Parent() {
  return (
      <Child data="this is props for child!"/>
  )
}

function Child(props) {
  return <h1>{props.data}</h1>
}

Props have 2 major characteristics.

1. Immutable

props must be read-only they should not be modified when passed to other components.

// 1st example
function Child(props) { // props is 1
  const modified = props.number + 1return <h1>{modified}</h1>
}

It is more easy to understand why props must be immutable according to the fact that props are more likely a reference from parent component. Therefore it is the parent components who owns the data.

// 2nd example
function Child(props) {
  props.data = "I want to change this"return <h1>{props.data}</h1>
}

2. Unidirectional

Props must be one-way data flow, which means props need to be passed only from parent components to child components.

Props-drilling occurs when a parent component passes data down to its children and then those children pass the same data down to their own children.

If the depth gets too deep, props-drilling could make React app difficult to manage and maintain.

What are the benefits?

Immutability and unidirection have benefits.

  1. comprehend the logic more quickly
  2. simplify the data flow

Props is one of the most important concept in React. Those two characteristics keep the React app consistent and reliable in controlling the flow of data between components.

profile
퇴사했지만, 코딩은 하고싶어

0개의 댓글