React Query

๊ณต์‹๋ฌธ์„œ

  • React application์—์„œ ์„œ๋ฒ„ ์ƒํƒœ์˜ fetching, caching, synchronizing and updating์„ ๋„์™€์ฃผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

import {
  useQuery,
  useMutation,
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from 'react-query'
import { getTodos, postTodo } from '../my-api'

// Create a client
const queryClient = new QueryClient()

function App() {
  return (
    // Provide the client to your App
    <QueryClientProvider client={queryClient}>
      <Todos />
    </QueryClientProvider>
  )
}
  • fetcherํ•จ์ˆ˜์— argument๊ฐ€ ํ•„์š”ํ•œ ๊ฒฝ์šฐ ์ต๋ช…ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด fetcherํ•จ์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•จ

  • key๋Š” ์บ์‹œ ์‹œ์Šคํ…œ์— ์ €์žฅ๋˜๊ณ  ์ž‘๋™ํ•˜๊ธฐ ์œ„ํ•ด ๊ณ ์œ ํ•œ ๊ฐ’์ด์–ด์•ผ ํ•จ

function Todos() {
  // Access the client
  const queryClient = useQueryClient()

  // Queries
  const query = useQuery('todos', getTodos)
  // TypeScript and argument
  const { isLoading, data } = useQuery<Interface>('todos', () => getTodos(argument))

  // Mutations
  const mutation = useMutation(postTodo, {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries('todos')
    },
  })

  return (
    <div>
      <ul>
        {query.data.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>

      <button
        onClick={() => {
          mutation.mutate({
            id: Date.now(),
            title: 'Do Laundry',
          })
        }}
      >
        Add Todo
      </button>
    </div>
  )
}

render(<App />, document.getElementById('root'))

React Query Devtools

๊ณต์‹๋ฌธ์„œ

  • React Query์˜ ๋ชจ๋“  ๋‚ด๋ถ€ ์ž‘๋™์„ ์‹œ๊ฐํ™” ํ•˜์—ฌ ๋ณด์—ฌ์คŒ

  • ์บ์‹œ์— ์–ด๋–ค query๊ฐ€ ์žˆ๋Š”์ง€์™€ Data Explorer ์ œ๊ณต

Import the Devtools

import { ReactQueryDevtools } from "react-query/devtools";

Floating Mode

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      // The rest of your application
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

Last updated