Skip to content

React

React JS는 페이스북과 인스타그램의 웹 UI를 개발할 때 사용하려고 만든 자바스크립트 라이브러리이다. 또한 Backbone.js와 Angular.js와 같이 이를 이용해 웹의 Front를 자유자재로 다룰 수 있으므로 나는 웹 프론트 프레임워크(Web Front Framework)라고도 생각한다.

React JS의 가장 큰 특징이자 사용하는 이유로는 지속해서 데이터가 변화하는 대규모 에플리케이션을 구축할 수 있다이다. React에서 Component를 사용하여 웹 UI를 구축하며 데이터가 변하는 Component만을 다시 rendering해서 변화된 데이터를 표시한다.

Categories

Hooks

Examples

Libraries

i18n

케로셀(Carousel)은 슬라이드 이미지 이다.

  • React-Slick - 문서도 깔끔하고 전형적인 슬라이드 느낌을 줄 수 있습니다. 문서가 워낙 정리가 잘 돼있다보니, 여러 예시들을 볼 수 있는 장점이 있네요
  • React-Material-Ui-Carousel - material-ui 와 연계성이 좋고 슬라이드가 넘어가는 애니메이션 설정이나, 화살표 설정 등 디테일한 설정을 변경할 수 있는 장점이 있습니다.
  • React Responsive Carousel - 반응형 슬라이드를 제공합니다. 이 라이브러리는 이미지 캐로셀만 지원하는 것 같더라구요! 이건 사용은 못해보았는데 npm 에서 다운로드 수가 압도적이길래 넣어봤습니다.

Window

  • react-window
  • react-virtualized-auto-sizer - HOC that grows to fit all of the available space and passes the width and height values to its child.
  • react-window-infinite-loader - Helps break large data sets down into chunks that can be just-in-time loaded as they are scrolled into view. It can also be used to create infinite loading lists (e.g. Facebook or Twitter).
  • react-vtree - Lightweight and flexible solution to render large tree structures (e.g., file system).

Eject

Animation

Frameworks

UI Frameworks

Performance - Block DOM

Database

  • GoatDB - Deno, React를 위한 경량 NoDB

ETC

Recommand Libraries

2022년 현재 React로 앱 개발할 때 추천 라이브러리들

  • React 프로젝트 생성 : 클라이언트에는 Vite/CRA, 서버에는 Next.js/Remix/Gatsby
  • React State 관리 : useState/useReducer, useContext, Redux
  • React Data Fetching : React Query (REST APIs, GraphQL APIs) + axios, Apollo Client
  • Routing with React Router
  • CSS Styling in React : CSS-in-CSS, CSS-in-JS/Emotion/Stitches, Functional CSS with Tailwind CSS
  • React UI Libraries : Material UI(가장 인기), Mantine(추천), Chakua UI(추천), Ant Design, Radix, Primer, NextUI, Tailwind UI (not free), Semantic UI, React Bootstrap
  • React Animation Libraries : Framer Motion (가장 추천), react-spring (종종 추천), react-motion, react-move, Animated (React Native)
  • Visualization and Chart Libraries in React : Recharts, react-chartjs, nivo, visx, Victory
  • Form Libraries in React : React Hook Form + yup/zod
  • React Type Checking : 그냥 TypeScript 쓰세요
  • React Code Structure: Style and Format : ESLint + Prettier
  • React Authentication : Firebase, Auth0, AWS Cognito 같은 서비스/BaaS 선택
  • React Hosting : 풀 관리하려면 Digital Ocean, 아니면 Cloudflare Workers, Netlify, or Vercel (특히 Next.js), Firebase 쓴다면 Firebase Hosting
  • Testing in React : Jest + React Testing Library (most popular), Cypress
  • React and Immutable Data Structures : Immer
  • React Internationalization : FormatJS, react-i18next
  • Rich Text Editor in React : Draft.js, Slate.js, ReactQuill
  • Payments in React :PayPal, React Stripe Elements 또는 Stripe Checkout
  • Time in React : date-fns, Day.js, Luxon
  • React Desktop Applications : Electron, Tauri, NW.js, Neutralino.js
  • Mobile Development with React : React Native, Expo
  • React VR/AR : react-three-fiber, react-360, aframe-react
  • Design Prototyping for React : Figma, Zeplin, Excalidraw, InVision
  • React Component Documentation : Storybook, Docusaurus, Docz, Styleguidist

JUST THE UI

Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.

VIRTUAL DOM

React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.

DATA FLOW

React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.

with Axios

React:useState 또는 React:useReducer와 함께 사용하자.

CSS 적용 방법

JavaScript Object 이용

class MyJob extends React.Component {
  render() {
    const hstyle = {
      color: "black",
      backgroundColor: "blue",
      fontFamily: "Arial"
    }
    return (
      <div>
      <h1 style={hstyle}>Hello Style!</h1>
      </div>
    );
  }
}

아니면 CSS가 Tag 스타일로 이루어 져 있다면

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';

class MyJob extends React.Component {
  render() {
    return (
      <div>
      <h1>Hello Style!</h1>
      </div>
    );
  }
}

CSS를 class 로 적용해야 할 경우

.mainBody {
  background-color: white;
  color: blue;
  margin: 10px;
  font-family: Arial;
  text-align: center;
}

React 적용시:

import React from 'react';
import ReactDOM from 'react-dom';
import styles from './App.css';

class MyJob extends React.Component {
  render() {
    return (
      <div>
      <h1 className={styles.mainBody}>Hello Style!</h1>
      </div>
    );
  }
}

onClick event handler prototype

function handleClick(event: React.MouseEvent<HTMLDivElement, MouseEvent>) {
  event.preventDefault();
  console.info('You clicked a breadcrumb.');
}

export default function Search() {
  return (
    <div role="presentation" onClick={handleClick}>
      ...
    </div>
  );
}

ReactNode vs ReactElement

Tips

v-if같은 단항 조건으로 컴포넌트를 JAX에 추가하는 방법

&& 연산의 결과가 마지막 조건절의 결과를 반환하는 특성을 이용한다.

function Page() {
  return (
    <Box sx={{display: 'flex'}}>
      <Box />
      {workId !== 0 && drawer}
      <Box />
    </Box>
  );
}

React 기술 스택 2025

  • [React Tech Stack 2025]

2025년을 위한 Full-Stack React Tech Stack

SaaS 제품 또는 최소 기능 제품(MVP)을 개발하는 데 유용한 기술들을 소개

  • Next.js - 리액트 기반의 프레임워크로, 라우팅, 캐싱 등 다양한 기능을 기본 제공하며, 서버 컴포넌트 및 서버 함수와 같은 최신 리액트 기능을 통해 백엔드와의 연결을 지원함
  • Astro - 제품의 랜딩 페이지를 생성하기 위한 선택적 도구로, 빠른 랜딩 페이지 제작과 개발자 경험 향상을 위해 사용됨
  • Server Components - 서버에서 실행되어 데이터베이스 접근 등을 가능하게 하는 컴포넌트로, 풀스택 리액트 애플리케이션 개발 방식을 혁신함
  • Server Functions - 리액트 컴포넌트에서 서버 측 코드를 함수 호출만으로 실행할 수 있게 해주는 기능으로, API 엔드포인트를 자동 생성함
  • Server Actions - 서버 함수의 하위 집합으로, 사용성을 높이기 위한 라이브러리가 존재하지만, 직접 구현도 가능함
  • Tailwind CSS - 빠른 제품 개발과 장기적인 CSS 유지보수를 위해 추천되는 도구로, 익숙해지면 전통적인 CSS 방식으로 돌아가기 어려움
  • Shadcn UI - Tailwind CSS와 원활하게 통합되는 UI 라이브러리로, 버전이 없는 시스템을 제공하여 UI 관리에 신선한 접근 방식을 제시함
  • Lucide React - Shadcn UI와 함께 제공되는 아이콘 라이브러리로, 다른 대안이 나타나기 전까지는 교체 필요성이 낮음
  • TypeScript - 자바스크립트 프로젝트의 산업 표준으로, 개발자 경험 향상, 버그 감소, 코드 유지보수성 향상에 기여함
  • Zod - TypeScript와 잘 맞는 검증 라이브러리로, 주로 서버 측 검증에 사용되며, 클라이언트 측 폼은 네이티브 HTML 검증을 활용하여 복잡성을 줄임
  • nuqs - Next.js에서 URL 상태(예: 검색, 정렬, 페이지네이션)를 타입 안전하게 관리하기 위한 도구로, 다른 프레임워크에서는 내장 기능이나 다른 라이브러리를 사용할 수 있음
  • Zustand - 클라이언트 측 상태 관리를 위한 선택적 도구로, URL 상태, 클라이언트 측 데이터 캐싱, 서버 주도 리액트 애플리케이션의 발전으로 사용 빈도가 줄어듦
  • React Query - 무한 스크롤 등 복잡한 클라이언트 측 데이터 페칭에 사용되는 선택적 도구로, 프로젝트 복잡도가 낮을 경우 서버 컴포넌트만으로도 충분함
  • Prisma (ORM) - 안정적인 ORM 선택으로, 최신 트렌드에 따라 Drizzle로 대체할 수 있으나, 현재는 Prisma를 선호함
  • Supabase (데이터베이스) - Postgres 데이터베이스를 제공하는 서비스로, 유연성을 위해 데이터베이스만 사용하고 Prisma로 연결하여 다른 데이터베이스로의 교체를 용이하게 함
  • Lucia (인증) - 더 이상 유지보수되지 않지만, Oslo, Argon2, Arctic 등을 활용한 인증 시스템 구축 학습 자료로 사용되어, 서드파티 솔루션에 의존하지 않는 맞춤형 인증 시스템을 구현할 수 있음
  • S3 (파일 업로드) - AWS S3, 프리사인드 URL, AWS IAM을 활용하여 유연하고 저렴한 파일 저장 솔루션을 구축할 수 있으며, 대부분의 서드파티 서비스도 동일한 API를 사용하므로 필요 시 제공자를 변경하기 용이함
  • Inngest (큐) - 백엔드에서 복잡한 작업 조율을 위해 사용되는 도구로, 시간에 민감하지 않은 백그라운드 작업에 적합하며, 설정과 유지보수가 용이한 큐 시스템을 제공함
  • React Email + Resend - 전자는 리액트 컴포넌트로 이메일 템플릿을 생성하게 해주며, 후자는 이메일 전송을 위한 훌륭한 솔루션으로, 이전에 사용하던 Postmark에서 Resend로 전환하여 만족스러운 결과를 얻음
  • Vercel (호스팅) - 수년간 사용해 온 풀스택 애플리케이션 호스팅 솔루션으로, 자체 호스팅을 원할 경우 Hetzner/DigitalOcean과 Coolify를 추천함
  • CloudFlare (도메인) - 다양한 도메인 관리 경험 후, 현재는 CloudFlare의 우수한 UI와 DNS 레코드에 추가 정보를 첨부할 수 있는 기능으로 인해 만족스럽게 사용 중임
  • Stripe (결제 게이트웨이) - 수년간 사용해 온 결제 게이트웨이로, 훌륭한 문서와 API를 제공하지만, 기능과 API 범위가 확대되어 복잡해질 수 있음
  • 테스팅 및 도구 - React Testing Library와 Cypress/Playwright의 조합이 좋은 선택이며, ESLint(미래에는 Biome), Prettier를 추천함. UI 문서를 위해 여전히 Storybook을 사용하며, 터미널에서 TypeScript를 실행하기 위해 tsx를 사용함

Troubleshooting

Download the React DevTools

Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtools

걍 플러그인 다운로드 ㄱㄱ

Missing "key" prop for element in iterator

[eslint] Missing "key" prop for element in iterator [react/jsx-key]

루프할 때 Element 에 key prop를 추가해야 한다. 다음과 같이:

return (
  <Stack direction="row" spacing={1}>
    {real.map(x => (<Chip key={x.id} label={x.value} sx={getChipStyle(x.color)} />))}
  </Stack>
);

React Hook useEffect has a missing dependency: 'xxx'

ESLint: React Hook useEffect has a missing dependency: 'requestRows'. Either include it or remove the dependency array.(react-hooks/exhaustive-deps)

React Hook 으로 개발을 하다 보면 위 warning(경고)를 정말 많이 보실 것입니다. useEffect내에 사용하고 있는 state를 배열안에 추가시켜 달라는 의미입니다.

You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

해당 컴포넌트의 import를 다시 하거나 연결되어있는 컴포넌트들 중에 이름(대소문자 등)가 달라서 발생했을수도 있다.

Inkscape SVG Import 에러

SyntaxError: unknown file: Namespace tags are not supported by default. React's JSX doesn't support namespace tags. You can set `throwIfNamespace: false` to bypass this warning.

React 에서 xmlns:svg와 같은 XML Namespace 를 읽을 수 없으므로 xmlnsSvg 와 같은 형식으로 사용하라... 같은데 잘 작동하지 않았다.

Inkscape 에서 작업한 SVG를 저장할 경우 Optimized SVG 로 저장하면 된다.

  • check the following at the options:
    • Shorten color values
    • Convert CSS attributes to XML attributes
    • Collapse groups
    • Create groups for similar attributes
  • SVG Output:
    • Remove the XML declaration
    • Remove metadata
    • Remove comments
    • Format output with line-breaks and indentation

또는 scour 패키지를 사용하면 된다. 사용한 명령행은 다음과 같다:

scour answer-logo-onlytext.svg answer-logo-onlytext2.svg  --strip-xml-space --remove-descriptive-elements --enable-comment-stripping

react-hooks/rules-of-hooks

  Line 26:22:  React Hook "useLocation" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

한마디로 Hook 을 콜백에서 사용하지 말라는 의미이다.

react-hooks/exhaustive-deps

다음과 같은 에러가 출력될 수 있다.

src/components/ChargingCanvas.tsx
  Line 73:20:  Assignments to the 'preRectX' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect  react-hooks/exhaustive-deps

리액트로 개발 중에 이런 warning을 자주 본 적이 있다. 리액트 CRA(Create React App) 환경에서 기본적으로 설치되어있는 ESLint 플러그인이 표시해주는 warning이다.

React Hook useXXX has a missing dependency 라는 warning은, "hook에서 state, prop, 함수를 사용하고 있으면 의존성 배열에 넣어줘!" 라는 뜻이다.

리액트는 hook 내부에서 렌더 범위 안에 있는 값을 사용 중임에도 의도적으로 의존성 배열을 빈 배열로 두는 것을 권장하지 않는다. 하지만 warning이 알려주는대로 의존성 배열을 없애거나 필요한 의존성 배열을 추가해주면, 컴포넌트가 의도대로 동작하지 않거나 무한 루프를 경험하게 된다.

해결 방법은 useRef Hook 을 사용하는 방법 등이 있다.

앱 배포 후 브라우저 캐시를 클리어하지 않으면 최신버전으로 갱신되지 않는 현상

React:CacheBusting 항목 참조.

Consider adding an error boundary to your tree to customize error handling behavior

브라우저 오류에서 다음과 같은 에러가 출력될 수 있다:

The above error occurred in the <ReactDevOverlay> component:

ReactDevOverlay@webpack-internal:///(app-pages-browser)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:37:27

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

관련 내용은 React:ErrorBoundary 항목 참조.

결론부터 말하자면 layout.js 같은 곳에

<html>

태그와

<body>

태그 등이 잘 살아있는지 확인해 보자.

See also

Favorite site

Guide

Turorials

Article

References


  1. Blog.coderifleman.com_-_learning_react_01.pdf 

  2. Webframeworks.kr_-_start_react.pdf 

  3. Why_React_and_Server_side_rendering.pdf 

  4. Meetup_TOAST_Cloud_-Introduction_to_the_JavaScript_Framework_4-_React.pdf 

  5. Learn_Webpack_for_React_-_ko.pdf 

  6. Secure_login_handling_at_the_frontend.pdf 

  7. Blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior.pdf