react.js

[react 리액트] 초간단 useContext 사용법

코복이 2023. 7. 4. 11:49
728x90

 

1. useContext 왜 써?

prop Chain 방지

부모에서 자식 컴포넌트로 데이터를 전달하려면 props를 통해 전달하는데 그 깊이가 깊어지면 거쳐가는 컴포넌트가 많아지고 심지어 통과용으로만 전달하는 컴포넌트도 생기며 코드도 반복적으로 작성해줘야 한다. 그리고 이과정에서 변수명이 변경되면 하나하나 변경해주고 이 위치에서 어떤 이름이었는지 기억해야하는 등 번거로운 일이 발생한다.

 

 

 

 

2. 사용법

 

1) createContext() : 컨텍스트 생성

컨텍스트용 파일을 따로 생성해도 되고 아님 최상위 위치에서 선언해도 된다

createContext(괄호) 괄호 안의 값은 디폴트값이며 컨텍스트에 벨류로 아무것도 넣어주지 않았을 때 디폴트값을 반환한다.
import { createContext } from "react";

const UserContext = createContext([])

export default UserContext

 

 

2) <MyContext.Provider value={}> : 최상위 컴포넌트 감싸고 데이터 넣기

생성한 컨텍스트로 특정 컴포넌트를 감싸면 해당 컴포넌트의 자식은 모두 데이터를 원하는 위치에서 전달받을 수 있다. 그래서 보통 최상위 컴포넌트를 감싸준다.

이때 벨류에 값을 전달하는데 상태, 함수, 값 등등 원하는 건 다 된다.


value 속성에 [] 배열과 {} 객체를 전달하는 것은 다음과 같은 차이가 있다.

1. [] 배열:value={[userList, setUserList]}와 같이 배열을 전달하는 경우,
배열의 요소들이 순서대로 userList와 setUserList에 매핑.

컴포넌트 내에서 useContext(UserContext)를 사용하면, 해당 컨텍스트의 값을 배열로 받아올 수 있습니다.
예를 들어, const [userList, setUserList] = useContext(UserContext)와 같이 사용할 수 있습니다.

2. {} 객체:value={{userList, setUserList}}와 같이 객체를 전달하는 경우,
객체의 프로퍼티 이름이 컨텍스트의 값과 매핑됩니다.
컴포넌트 내에서 useContext(UserContext)를 사용하면, 해당 컨텍스트의 값을 객체로 받아올 수 있습니다. 예를 들어, const {userList, setUserList} = useContext(UserContext)와 같이 사용할 수 있습니다.

따라서 배열을 사용하면 순서에 따라 컨텍스트 값을 할당하고, 객체를 사용하면 프로퍼티 이름에 따라 컨텍스트 값을 할당합니다. 선택은 개발자에게 달려 있으며, 상황에 맞게 더 적합한 방법을 선택할 수 있습니다.
import { useState } from "react";
import "./App.css";
import AddUserForm from "./Component/AddUserForm";
import UserList from "./Component/UserList";
import UserContext from "./Context/userContext";

function App() {
  const [userList, setUserList] = useState([]);
  return (
    <div className="App">
      <UserContext.Provider value={[userList, setUserList]}>
        <AddUserForm />
        <UserList />
      </UserContext.Provider>
    </div>
  );
}

export default App;

 

 

3) const [data1, data2] = useContext(MyContext) : 데이터 사용할 컴포넌트에서 컨텍스트 작성

데이터 사용할 컴포넌트에서 react 훅인 useContext 와 내가 만든 Context를 모두 import 한다.
import { useContext, useRef } from "react";
import UserContext from "../Context/userContext";

const AddUserForm = () => {
  const nameRef = useRef("");
  const ageRef = useRef("");
  const [userList, setUserList] = useContext(UserContext);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const newUser = {
      name: nameRef.current.value,
      age: ageRef.current.value,
    };
    await fetch(
      "",
      {
        method: "POST",
        body: JSON.stringify(newUser),
      }
    )
      .then((res) => res.json())
      .then((data) => {
        newUser.id = data.name; // data.name 은 firebase 고유 id = key값
        setUserList([newUser, ...userList]);
      });
    // 입력 필드 초기화
    nameRef.current.value = "";
    ageRef.current.value = "";
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>Register Form</label>
      <div>
        <label>name</label>
        <input type="text" ref={nameRef} />
      </div>
      <div>
        <label>age</label>
        <input type="number" ref={ageRef} />
      </div>
      <button type="submit">+Add</button>
    </form>
  );
};

export default AddUserForm;

 

 

3. 마무리

Lean Code를 위해 Context가 꼭 필요할 때가 있고 오히려 번잡할 때가 있다.

props를 넘겨주는 것과 Context를 상황에 맞게 조합하여 사용하자!

728x90