import { useState } from 'react'
import Viewer from './components/Viewer';
import Controller from './components/Controller';
function App() {
const [count, setCount] = useState(0);
const onClickBtn = (value) => {
setCount(count + value)
console.log(count)
}
return (
<div className='App'>
<h1>Simple Counter</h1>
<section>
<Viewer count={count}/>
</section>
<section>
<Controller onClickBtn={onClickBtn}/>
</section>
</div>
)
}
export default App;
setCount
는 비동기적으로 동작하므로 setCount
가 pending
상태가 되면 console.log
를 실행한 뒤에 fulfilled
상태가 된 setCount
의 결과를 반환한다.
Every React component goes through the same lifecycle:
- A component mounts when it’s added to the screen.
- A component updates when it receives new props or state, usually in response to an interaction.
- A component unmounts when it’s removed from the screen.
모든 리액트 컴포넌트는 같은 생명주기를 가진다.
Before getting to Effects, you need to be familiar with two types of logic inside React components:
- Rendering code (introduced in Describing the UI) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. Rendering code must be pure. Like a math formula, it should only calculate the result, but not do anything else.
- Event handlers(introduced in Adding Interactivity) are nested functions inside your components that do things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain “side effects” (they change the program’s state) caused by a specific user action (for example, a button click or typing).
Effect에 가기 전에, 리액트 컴포넌트의 두 가지 내부 논리에 익숙해져야 한다.
Effects let you specify side effects that are caused by rendering itself, rather than by a particular event. Sending a message in the chat is an event because it is directly caused by the user clicking a specific button. However, setting up a server connection is an Effect because it should happen no matter which interaction caused the component to appear. Effects run at the end of a commit after the screen updates. This is a good time to synchronize the React components with some external system (like network or a third-party library).
Effect는 특정 이벤트가 아닌 랜더링 자체로 발생하는 사이드 이펙트를 명시할 수 있다. 채팅에서 메시지를 보내는 것은 사용자가 특정 버튼을 클릭함으로서 직접적으로 발생하기 때문에 이벤트이다. 하지만, 서버 연결을 설정하는 것은 컴포넌트를 나타내기 위해 발생하는 상호작용에 관계없이 일어나야 하기 때문에 Effect다. Effect는 화면 업데이트 후에 커밋이 끝날 때 실행된다. 리액트 컴포넌트를 일부 외부 시스템(네트워크 또는 서드파티 라이브러리)과 동기화하기 좋은 시간이다.
컴포넌트의 동작에 따라 파생되는 효과를 뜻한다.
동작 | 사이드 이펙트 |
---|---|
컴포넌트 내부의 값 변경 | 콘솔에 변경된 값 출력 |
컴포넌트 마운트 | 콘솔에 "mount" 출력 |
컴포넌트 업데이트 | 콘솔에 "update" 출력 |
컴포넌트 언마운트 | 콘솔에 "unmount" 출력 |
import { useEffect } from "react";
컴포넌트의 최상위 레벨에서 호출하고 Effect 내부에 코드를 추가한다.
const MyComponent = () => {
useEffect(() =>{
//요기의 코드는 매 렌더링 후 실행
})
return <div></div>
}
컴포넌트가 렌더링될 때마다 react는 화면을 업데이트하고 useEffect
는 내부의 코드를 실행한다. useEffect
는 해당 렌더링이 화면에 반영될 때까지 코드 일부의 실행을 지연한다.
useEffect
호출의 두 번째 인자로 의존성 배열을 지정하여 리액트가 불필요하게 Effect를 다시 실행하지 않도록 지정할 수 있다.
const MyComponent = () => {
useEffect(() =>{
//요기의 코드는 매 렌더링 후 실행
}, [])
return <div></div>
}
useEffect는 의존성 배열에 존재하는 변수가 변경될 때 동작하는 조건문이다.