Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 169 additions & 0 deletions week3/[3주차]강예린.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
### useState

가장 기본적인 Hook이며 함수 컴포넌트에서도 가변적인 상태를 지닐 수 있게 해줌

*Counter.js*

```jsx
import { useState } from "react";
const Counter = () => {
const [counter, setCounter] = useState(0);

return (
<div>
<p>현재 카운터 값은 {counter}</p>
<button onClick={()=> setCounter(counter+1)}>+1</button>
<button onClick={()=> setCounter(counter-1)}>-1</button>
</div>
);
};

export default Counter;
```

### useEffect

useEffect는 리액트 컴포넌트가 렌더링될 때마다 **특정 작업을 수행하도록 설정**할 수 있는 Hook

*info.js*

```jsx
import { useState, useEffect } from "react";

const Info = () => {

const [name, setName]= useState('');
const [nickname, setNickname] = useState('');

useEffect(()=>{
console.log('렌더링 완료되었습니다.');
console.log({
name,
nickname
});
});

const onChangeName= e => setName(e.target.value);
const onChangeNickName= e => setNickname(e.target.value);

return(
<div>
<div>
<input value={name} onChange={onChangeName}/>
<input value={nickname} onChange={onChangeNickName}/>
</div>
<div>
<div>
<b>이름: </b> {name}
</div>
<div>
<b>닉네임: </b> {nickname}
</div>
</div>
</div>
);
}
export default Info;
```

**마운트될 때만 실행하고 싶을 때**

useEffect에서 설정한 함수를 컴포넌트가 화면에 맨 처음 렌더링될 때만 실행하고 업데이트될 때 실행하지 않으려면 함수의 두번째 파라미터로 비어 있는 배열을 넣어 주면 됨

*info.js*

```jsx
useEffect(()=> {
console.log('마운트될 때만 실행됩니다.')
}, []);
```

**특정 값이 업데이트될 떄만 실행하고 싶을 때**

두번째 파라미터로 전달되는 배열 안에 검사하고 싶은 값을 넣어주면 됨

*info.js*

```jsx
useEffect(()=> {
console.log(name)
}, [name]);
```

useEffect는 기본적으로 렌더링되고 난 직후마다 실행됨 → 두번째 파라미터 배열에 무엇을 넣는지에 따라 실행되는 조건이 다름

**뒷정리하기**

컴포넌트가 언마운트되기 전이나 업데이트되기 직전에 어떠한 작업을 수행

→ useEffect의 뒷정리(cleanup) 함수 반환

*info.js*

```jsx
useEffect(()=> {
console.log('effect')
console.log(name)
return () => {
console.log('cleanup')
console.log(name)
};
}, [name]);
```

**App컴포넌트에서 Info 컴포넌트의 가시성을 바꿀 수 있게 useState 사용**

*info.js*

```jsx
import Info from "./Info";
import { useState } from "react";

const App = () => {
const [visible, setVisible] = useState(false);
return (
<div>
<button onClick={()=>{
setVisible(!visible);
}}>
{visible ? '숨기기' : '보이기'}
</button>

{/*hr태그는 수평 가로선을 의미*/}

<hr/>
{visible && <Info/>}

</div>
);

};

export default App;
```

```jsx
useEffect(()=>{
(수행되는 작업)
}, [의존되는 값들])
```

의존되는 값의 배열이 비어있으면, 컴포넌트가 처음 생성될 때에만 작업이 실행된다.

컴포넌트가 화면에서 사라질 때는 return 해서 코드를 작성해줌

오직 언마운트될 때만 뒷정리 함수를 호출하고 싶다면 빈 배열을 두 번째 파라미터에 넣음

```jsx
useEffect(() => {
// mount
console.log('컴포넌트가 화면에 나타남');

return() => {
// unmount
console.log('컴포넌트가 화면에서 사라짐');
}
}, [])
```

출처: 길벗 리액트를 다루는 기술
24 changes: 24 additions & 0 deletions week3/todoList/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
16 changes: 16 additions & 0 deletions week3/todoList/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# React + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## React Compiler

The React Compiler is not enabled on this template. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).

## Expanding the ESLint configuration

If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
29 changes: 29 additions & 0 deletions week3/todoList/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import { defineConfig, globalIgnores } from 'eslint/config'

export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{js,jsx}'],
extends: [
js.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
rules: {
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
},
},
])
17 changes: 17 additions & 0 deletions week3/todoList/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="ko">
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap" rel="stylesheet">

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Todo List</title>
<meta name="description" content="Todo List" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
Loading