본 글은 udemy의
React- The Complete Guide 2024 (incl. Next.js, Redux)를
수강하며 작성한 글입니다.
리액트의 핵심적인 부분들에 대해 알아보자.
Components, JSX, Props, State & More
"React Apps are built by combining components."
=> Reusable Building Blocks, Related Code Lives Together, Separation of Concerns
HTML, CSS, JS => React Component (JSX) - (transpile) > Browser DOM
*JSX : JavaScript Syntax Extension
Rules of React Components
1. Name Starts With Uppercase Character
2. Returns "Rendable" Content (In most cases, return JSX)
Props
props.children : component tag의 시작과 끝 사이의 내용에 접근할 수 있도록 도와줌.
event handler : on____ props ex) onClick, onSelect...
"By default, React Components Execute only once.
You have to tell react if a component should be executed again. "
React Hooks : use____
Manage data & tell React to re-execute a component function via React's useState() Hook
Rules of Hooks
1. Only call Hooks inside of Component Functions
2. Only call Hooks on the top level
const [state, setState] = useState (' ');
Current state value, State updating function, Initial state value
상태에 따라 다른 내용을 출력하는 방법
{selected === undefined} <> '선택되지 않았을 때 보여줄 div </> + ~ 반대의 경우 출력문 작성
{! selected ? <> '선택되지 않았을 때 보여줄 div : null}
{! selected ? <> '선택되지 않았을 때 보여줄 div</> : < > "선택 되었을 때 보여줄 div </>}
! selected && '선택되지 않았을 때 보여줄 div => 조건이 true라면 &&뒤를 출력
변수로 선언후 if문을 통한 설정
List data 동적 출력
.map()
// CoreConcept.jsx
export default function CoreConcept({ image, title, description }) {
return (
<li>
<img src={image} alt={title} />
<h3>{title}</h3>
<p>{description}</p>
</li>
);
}
//data.js 中
export const CORE_CONCEPTS = [
{
image: componentsImg,
title: 'Components',
description:
'The core UI building block - compose the user interface by combining multiple components.',
},
...
];
// App.jsx 中
{CORE_CONCEPTS.map((conceptItem) => (
<CoreConcept key={conceptItem.title} {...conceptItem} />
))}
! 사용 시 리액트가 컴포넌트를 구별하여 렌더링을 최소화 하기 위해 고유한 값으로 key 설정하기.
Deep Dive
이론상 JSX의 도움 없이도 리액트 앱을 빌드 할 수 있음을 인지하자.
React.createElement( ) 사용하여 빌드 과정이 필요 없는 프로젝트를 진행할 수 있다.
하지만, JSX를 사용하는 방식이 보다 사용하기 쉽고, 가독성이 좋기에, JSX를 주로 사용한다.
JSX
Error : JSX expressions must have one parent element.
why? js에서는 2개이상의 값을 return하는 것을 허락하지 않기 때문에
초기 : <div> </div>로 감싸기 => DOM에 중복되는 요소가 발생
중기 : fragment component 사용 <Fragment> </Fragment>
현재 : < > </ > 보다 짧은 대안을 제시
return (
<>
...
</>
)
Components
작은 단위의 하위 컴포넌트 여러 개로 나누어 사용하는 것이 바람직 (책임 분할)
props는 자동으로 연동되지 않음
매 속성을 지정해주기 어렵기에, forward props(proxy props) pattern을 사용
{children, ...props}
자주 사용하는 component에 대해 재사용 할 수 있도록 만들기.
컴포넌트 식별자 속성값으로 받기.
1. 받는 쪽 component에서 custom component로 사용 가능해야함 (대문자로 시작)
2. 식별자 - 내부요소 : 'string' , component function : { Component Function }
초기 default 값 지정 가능.
모든 콘텐츠가 컴포넌트에 보관될 필요가 없는 이유
정적인 마크업이 있다면 index.html에 바로 작성하여도 무방.
public/ 폴더에 저장되어 있는 이미지들은 공개적으로 제공되며, 파일명으로 경로 지정이 가능하다
그 외 src/assets/폴더와 같은 곳에 저장되어있는 파일은 공개적으로 제공되지 않아, 웹사이트 방문자가 접근 할 수 없다.
빌드 프로세스에 의해 웹 사이트 제공 직전에 public/에 삽입된다.
일반적으로 컴포넌트에서 사용하는 이미지는 src/폴더 내에 두는 것이 바람직하다.
상태를 업데이트 할 때, 객체나 배열이라면 복제 후 수정하여 변경 불가능하게 하는 것이 좋다.
그렇지 않다면, 기존의 참조 값을 바로 업데이트 하기에 리액트가 실행 예정인 시점보다 빨리 적용되어 버그나 오류가 발생할 수 있다,
const updatedBoard = [
...prevGameBoard.map((innerArray) => [...innerArray]), // 2차원 배열 깊은 복사를 위함.
];
Lifting State Up
When ? State value that's needed by both Child1 & Child2 components.
Lift the state up to the closest ancestor component that has access to all components that need to work with that state.
Ancestor passes a function that eventually changes the state via props to the child component.
상태를 하나 더 만들어 크게 다를 것 없는 정보를 저장하는 것은 불필요하다.
Tic-tac-toe-starting-project
Practice Project
event.target.value : JS에서 항상 string 으로 얻어옴.
[inputIdentifier]: +newValue,
값을 가져오는 부분에 '+' 를 붙여줌으로써 숫자로 인식하게끔 만들 수 있음
GitHub - academind/react-complete-guide-course-resources: React - The Complete Guide Course Resources (Code, Attachments, Slides
React - The Complete Guide Course Resources (Code, Attachments, Slides) - academind/react-complete-guide-course-resources
github.com
GitHub - codrae/React-The-Complete-Guide
Contribute to codrae/React-The-Complete-Guide development by creating an account on GitHub.
github.com