1. 비동기 프로그래밍
- JavaScript의 비동기 처리 개념: Callback, Promise, async/await
- fetch API 및 axios를 활용한 데이터 요청
2. json-server
- 가짜 REST API 서버를 생성하여 개발 환경에서 API 요청 테스트 가능
- 설치 방법:
npm install -g json-server yarn add json-server yarn add json-server -D # 개발 환경인 경우, -D 옵션을 함께 입력합니다.
- 사용법:
yarn json-server db.json --port 4000
- db.json 파일 예시:
{ "posts": [ { "id": 1, "title": "Hello World", "author": "John" } ] }
3. axios
- 설치 방법:
npm install axios yarn add axios
- 사용 예시:
// url에는 서버의 url이 들어가고, config에는 기타 여러가지 설정을 추가할 수 있습니다. // config는 axios 공식문서에서 확인하세요. axios.get(url[, config]) // GET(url은 매개변수, 대괄호([]) 안의 값은 선택 입력사항입니다. axios.post(url[, data[, config]]) // POST 추가 요청 axios.delete(url[, config]) // DELETE 삭제 요청 axios.patch(url[, data[, config]]) // PATCH 수정 요청
- Custom instance 생성 및 interceptors 활용 가능
// src/App.js
import React, { useEffect, useState } from "react";
import axios from "axios"; // axios import 합니다.
const App = () => {
const [todos, setTodos] = useState(null);
// axios를 통해서 get 요청을 하는 함수를 생성합니다.
// 비동기처리를 해야하므로 async/await 구문을 통해서 처리합니다.
const fetchTodos = async () => {
const { data } = await axios.get("http://localhost:4000/todos");
setTodos(data); // 서버로부터 fetching한 데이터를 useState의 state로 set 합니다.
};
// 생성한 함수를 컴포넌트가 mount된 후 실행하기 위해 useEffect를 사용합니다.
useEffect(() => {
// effect 구문에 생성한 함수를 넣어 실행합니다.
fetchTodos();
}, []);
// data fetching이 정상적으로 되었는지 콘솔을 통해 확인합니다.
console.log(todos);
return <div>App</div>;
};
export default App;
4. TanStack Query
- 서버 상태 관리를 위한 라이브러리
- 설치 방법:
//프로젝트 생성 yarn create vite tanstack-query-app --template react //설치 yarn add @tanstack/react-query
- 기본 사용법:
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import axios from 'axios'; const fetchPosts = async () => { const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; }; function Posts() { const queryClient = useQueryClient(); const { data, error, isLoading } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts }); const mutation = useMutation( (newPost) => axios.post('https://jsonplaceholder.typicode.com/posts', newPost), { onSuccess: () => { queryClient.invalidateQueries(['posts']); } } ); if (isLoading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <button onClick={() => mutation.mutate({ title: 'New Post' })}>Add Post</button> <ul> {data.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> </div> ); }
5. Zustand
- 가벼운 상태 관리 라이브러리
- 작은 규모의 애플리케이션에서는 상태관리가 간단하지만, 애플리케이션이 커질수록 상태관리는 점점 더 복잡해집니다.
- 설치 방법:
npm install zustand yarn add zustand
- 사용법:
// src > zustand > bearsStore.js import { create } from "zustand"; const useBearsStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), })); export default useBearsStore;
// src > App.jsx
import "./App.css";
import useBearsStore from "./zustand/bearsStore";
function App() {
const bears = useBearsStore((state) => state.bears);
const increasePopulation = useBearsStore((state) => state.increasePopulation);
return (
<div>
<h1>{bears} around here ...</h1>
<button onClick={increasePopulation}>one up</button>
</div>
);
}
export default App;
6. UX 향상을 위한 Throttling & Debouncing
- Throttling: 일정 시간마다 실행 (scroll 이벤트 최적화)
- Debouncing: 일정 시간 이후 실행 (검색 입력 필드 최적화)
- 예제 (Debounce 적용):
import { useState } from 'react'; import { debounce } from 'lodash'; function SearchBar() { const [query, setQuery] = useState(''); const handleSearch = debounce((text) => console.log(text), 300); return <input onChange={(e) => handleSearch(e.target.value)} placeholder="Search..." />; }
7. 인증 및 인가
(1) 인증, 인가의 개념
- 인증(Authentication)이란 서비스를 이용하려는 유저가 등록된 회원인지 확인하는 절차입니다.
- 우리는 간단히 ‘로그인’ 과정이구나!! 하고 이해하면 됩니다 😎
- 인가(Authorization)이란, 인증을 받은 유저가 특정 리소스에 접근할 수 있는 권한이 있는지 확인하는 절차입니다.
- 로그인이 일어난 이후의 과정으로 이해해주세요
- JWT 기반 인증 구현 가능
- React에서 로그인 상태 관리 예제:
import { useState } from 'react'; function Login() { const [token, setToken] = useState(null); const handleLogin = async () => { const response = await fetch('/api/login', { method: 'POST' }); const data = await response.json(); setToken(data.token); }; return <button onClick={handleLogin}>Login</button>; }
8. Tailwind CSS
- 설치 방법:
npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p yarn add tailwindcss postcss autoprefixer npx tailwindcss init -p
- 설정 (tailwind.config.js):
module.exports = { content: ['./src/**/*.{js,jsx,ts,tsx}'], theme: { extend: {}, }, plugins: [], };
- 기본 사용법
// src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
- 사용 예시:
function Button() { return <button className="bg-blue-500 text-white px-4 py-2 rounded">Click Me</button>; }
9. 반응형 웹 개발
- CSS Media Queries, Tailwind의 sm, md, lg 클래스 활용 가능 (스크린 사이즈 지정)
- 예제:
function ResponsiveDiv() { return <div className="p-4 sm:bg-red-500 md:bg-green-500 lg:bg-blue-500">Responsive</div>; }
Variant | Minimum | widthCSS |
@3xs | 16rem (256px) | @container (width >= 16rem) { … } |
@2xs | 18rem (288px) | @container (width >= 18rem) { … } |
@xs | 20rem (320px) | @container (width >= 20rem) { … } |
@sm | 24rem (384px) | @container (width >= 24rem) { … } |
@md | 28rem (448px) | @container (width >= 28rem) { … } |
@lg | 32rem (512px) | @container (width >= 32rem) { … } |
@xl | 36rem (576px) | @container (width >= 36rem) { … } |
@2xl | 42rem (672px) | @container (width >= 42rem) { … } |
@3xl | 48rem (768px) | @container (width >= 48rem) { … } |
@4xl | 56rem (896px) | @container (width >= 56rem) { … } |
@5xl | 64rem (1024px) | @container (width >= 64rem) { … } |
@6xl | 72rem (1152px) | @container (width >= 72rem) { … } |
@7xl | 80rem (1280px) | @container (width >= 80rem) { … } |
'TIL' 카테고리의 다른 글
||(논리OR연산자) vs ??(Null 병합 연산자) (0) | 2025.03.04 |
---|---|
🤔 npm vs yarn 차이점 (0) | 2025.02.26 |
🔍 일반 객체 ({}) vs Map (0) | 2025.02.14 |
코드로 소통하기 (깃허브 쓰는 방법) (0) | 2025.02.11 |
Hook (0) | 2025.01.31 |