React.js + Next.js

데이터 관리와 전달

진호우 2024. 5. 30. 13:45

리액트 프로젝트에서 데이터를 전달하는 방법에는 여러 가지가 있지만, 가장 일반적인 두 가지 방법은 props와 Context API의 Provider를 사용하는 것이다. 이 두 가지 방법과 zustand 라이브러리를 통한 방법을 알아보자.

 

1. Props를 사용한 데이터 전달

개념

Props는 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하기 위한 방법이다. 컴포넌트를 재사용하고, 데이터를 명시적으로 전달할 수 있는 방법이다.

 

ParentComponent.js

import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const data = "Hello from Parent";

  return (
    <div>
      <ChildComponent data={data} />
    </div>
  );
};

export default ParentComponent;

ChildComponent.js

import React from 'react';

const ChildComponent = (props) => {
  return (
    <div>
      {props.data}
    </div>
  );
};

export default ChildComponent;

 

장단점

  • 장점:
    • 명확한 데이터 흐름: 부모에서 자식으로 데이터가 명확하게 전달된다.
    • 단순성: 추가 설정이 필요 없다.
    • 타입 안정성: TypeScript와 PropTypes로 타입 검증이 가능하다.
  • 단점:
    • 프로퍼티 드릴링: 여러 단계의 컴포넌트를 거쳐야 하는 경우 비효율적이다.
    • 유연성 부족: 전역 상태 관리에는 적합하지 않다.

 

2. Context API의 Provider를 사용한 데이터 전달

DataContext.js

import { createContext } from 'react';

const DataContext = createContext();

export default DataContext;

 

ParentComponent.js

import React from 'react';
import DataContext from './DataContext';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const user = {
    name: "Jane Smith",
    age: 25,
    email: "jane.smith@example.com"
  };

  return (
    <DataContext.Provider value={user}>
      <ChildComponent />
    </DataContext.Provider>
  );
};

export default ParentComponent;

 

ChildComponent.js

import React, { useContext } from 'react';
import DataContext from './DataContext';

const ChildComponent = () => {
  const user = useContext(DataContext);
  const { name, age, email } = user;

  return (
    <div>
      <h1>User Information</h1>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
    </div>
  );
};

export default ChildComponent;

 

장단점

  • 장점:
    • 전역 상태 관리: Provider 내부 어디서든 데이터를 사용할 수 있다.
    • 코드 간소화: 중간 컴포넌트에 props를 전달할 필요가 없다.
    • 유연성: 다양한 데이터를 전역적으로 관리할 수 있다.
  • 단점:
    • 복잡성 증가: 작은 프로젝트에서는 불필요하게 복잡할 수 있다.
    • 디버깅 어려움: 데이터 흐름을 추적하기 어려울 수 있다.
    • 성능 문제: Context 값 변경 시 하위 컴포넌트가 모두 다시 렌더링될 수 있다.

 

 

3. Zustand와 React-query를 사용한 데이터 전달

Context API보다 더 간단하고 직관적으로 사용할 수 있을 것 같다.

useUserStore.js

import create from 'zustand';

const useUserStore = create((set) => ({
  user: {
    name: "Alice Johnson",
    age: 28,
    email: "alice.johnson@example.com",
  },
  setUser: (newUser) => set({ user: newUser }),
}));

export default useUserStore;

 

ParentComponent.js 파일

Zustand 스토어에서 데이터를 가져오도록 한다.

import React from 'react';
import useUserStore from '../store/useUserStore';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const { user, setUser } = useUserStore();

  const updateUser = () => {
    setUser({
      name: "Bob Smith",
      age: 35,
      email: "bob.smith@example.com",
    });
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <button onClick={updateUser}>Update User</button>
      <ChildComponent />
    </div>
  );
};

export default ParentComponent;

 

 

ChildComponent.js 파일

Zustand 스토어에서 데이터를 가져오도록 한다.

import React from 'react';
import useUserStore from '../store/useUserStore';

const ChildComponent = () => {
  const { user } = useUserStore();
  const { name, age, email } = user;

  return (
    <div>
      <h1>User Information</h1>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
    </div>
  );
};

export default ChildComponent;

 

장단점

장점

  • 간편성: Zustand는 간단하고 직관적인 API를 제공하여 빠르게 상태 관리를 설정할 수 있다.
  • 성능 최적화: 필요한 부분만 리렌더링하여 성능을 최적화한다.
  • 유연성: React 외의 라이브러리와도 잘 통합된다.
  • 가벼움: Zustand는 경량 라이브러리로, 번들 크기를 최소화할 수 있다.

단점

  • 커뮤니티: Redux와 같은 더 오래된 라이브러리에 비해 커뮤니티와 생태계가 작을 수 있다.
  • 러닝커브: 새로운 도구를 배우는 데 시간이 필요할 수 있다.

 

각각 상황에 맞게 데이터관리를 해보자~~