Post

React Query에 대해 들어봤는지?

안녕하세요! 오늘은 React Query에 대해 알아보겠습니다. React Query는 서버 상태 관리를 쉽게 할 수 있게 해주는 라이브러리로, 비동기 데이터 페칭, 캐싱, 동기화 등을 간편하게 처리할 수 있습니다.

React Query란?

1. React Query 정의

React Query는 서버에서 데이터를 가져오고 캐싱하며, 이 데이터를 컴포넌트에서 쉽게 사용할 수 있게 해주는 라이브러리입니다. 주로 REST API나 GraphQL과 같은 비동기 데이터 소스를 다룰 때 유용하게 사용됩니다.

2. React Query의 주요 특징

2.1 간편한 데이터 페칭

React Query는 데이터 페칭을 매우 간단하게 처리할 수 있게 해줍니다. useQuery 훅을 사용하여 데이터를 페칭하고, 로딩 상태와 에러 상태를 관리할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from 'react';
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchPosts = async () => {
    const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
    return data;
};

function Posts() {
    const { data, error, isLoading } = useQuery('posts', fetchPosts);

    if (isLoading) return <div>Loading...</div>;
    if (error) return <div>Error: {error.message}</div>;

    return (
        <ul>
            {data.map(post => (
                <li key={post.id}>{post.title}</li>
            ))}
        </ul>
    );
}

export default Posts;

2.2 캐싱 및 자동 리페치

React Query는 데이터 캐싱을 자동으로 처리하여, 동일한 데이터를 다시 요청할 때 네트워크 요청을 줄여줍니다. 또한, 데이터가 변경될 때 자동으로 리페치하여 최신 상태를 유지할 수 있습니다.

2.3 데이터 동기화

React Query는 서버 데이터와 클라이언트 데이터를 동기화하는 기능을 제공합니다. 데이터가 변경되면 자동으로 업데이트되며, 실시간으로 최신 데이터를 유지할 수 있습니다.

2.4 폴링 및 리페치 간격 설정

React Query는 폴링과 리페치 간격을 설정하여 주기적으로 데이터를 가져올 수 있습니다. 이를 통해 실시간으로 데이터를 업데이트할 수 있습니다.

1
2
3
const { data, error, isLoading } = useQuery('posts', fetchPosts, {
    refetchInterval: 60000, // 1분마다 리페치
});

2.5 뮤테이션

React Query는 useMutation 훅을 제공하여 데이터의 생성, 업데이트, 삭제와 같은 변화를 처리할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React from 'react';
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

const addPost = async (newPost) => {
    const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', newPost);
    return data;
};

function AddPost() {
    const queryClient = useQueryClient();
    const mutation = useMutation(addPost, {
        onSuccess: () => {
            // 포스트 목록을 리페치
            queryClient.invalidateQueries('posts');
        },
    });

    const handleSubmit = (event) => {
        event.preventDefault();
        const newPost = {
            title: event.target.elements.title.value,
            body: event.target.elements.body.value,
        };
        mutation.mutate(newPost);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input name="title" placeholder="Title" />
            <textarea name="body" placeholder="Body" />
            <button type="submit">Add Post</button>
        </form>
    );
}

export default AddPost;

3. React Query 설치 및 설정

설치

React Query는 npm 또는 yarn을 통해 설치할 수 있습니다.

1
npm install react-query

또는

1
yarn add react-query

설정

React Query를 사용하려면 QueryClientQueryClientProvider를 설정해야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from 'react-query';
import App from './App';

const queryClient = new QueryClient();

ReactDOM.render(
    <QueryClientProvider client={queryClient}>
        <App />
    </QueryClientProvider>,
    document.getElementById('root')
);

결론

React Query는 서버 상태 관리를 간편하게 처리할 수 있게 해주는 강력한 라이브러리입니다. 데이터 페칭, 캐싱, 동기화, 폴링, 뮤테이션 등 다양한 기능을 제공하여 개발자가 서버 데이터를 효율적으로 관리할 수 있도록 도와줍니다. React Query를 사용하면 코드의 복잡성을 줄이고, 애플리케이션의 성능을 향상시킬 수 있습니다.

오늘도 제 글을 읽어주셔서 감사합니다. 다음 시간에 더 유익한 주제로 찾아뵙겠습니다.

This post is licensed under CC BY 4.0 by the author.