공식 문서reactive variable이란?reactive variable 사용법creating (makeVar)Reading ( 값 읽기 )Modifying ( 값 수정 )Reacting쿼리에 의존시키기useReactiveVar (localState로 사용하기)
공식 문서
- apollo client
Reactive variables
공식문서 : https://www.apollographql.com/docs/react/local-state/reactive-variables/
reactive variable이란?
import { makeVar, useReactiveVar } from '@apollo/client';
AC3
(아폴로 클라이언트 3)에서 새로 나온 reactive variables
는 아폴로 클라이언트 캐시 외부의 local state를 나타내는 데 유용한 메커니즘이다. cache
와 별개이며 reactive variables
는 아폴로 클라이언트 캐시에 저장되지 않으므로 캐시된 유형의 엄격한 구조를 준수할 필요가 없고, 따라서 모든 유형과 구조의 데이터를 저장할 수 있다. 또한 GraphQL 구문을 사용하지 않고도 애플리케이션의 어디에서나 이러한 변수와 상호 작용할 수 있다.가장 중요한 것은
reactive variable
의 값을 수정하면- 해당 변수를 의존하고 있는 모든 활성 쿼리의 업데이트가 트리거된다. (refetch 된다는 의미)
- 또한
useReactiveVar
React hook을 사용하는 컴포넌트의 React state를 업데이트하여 컴포넌트를 리렌더링 시킨다.
reactive variable 사용법
creating (makeVar)
reactive variable
을 만드는 방법import { makeVar } from '@apollo/client'; const cartItemsVar = makeVar([]);
makeVar
는 reactive variable의 값을 읽을 수도, 수정할 수도 있는 함수를 반환한다.Reading ( 값 읽기 )
값을 읽기 위해서는 makeVar()에서 반환된 함수를 인자 없이 호출하면 된다.
const cartItemsVar = makeVar([]); // Output: [] console.log(cartItemsVar());
Modifying ( 값 수정 )
reactive variable
의 값을 변경하기 위해서는 하나의 값을 인자로 전달해서 호출하면 된다.const cartItemsVar = makeVar([]); // setter cartItemsVar([100, 101, 102]); // getter // Output: [100, 101, 102] console.log(cartItemsVar()); // setter cartItemsVar([456]); // getter // Output: [456] console.log(cartItemsVar());
Reacting
이름에서도 알 수 있듯이,
reactive variable
는 application에서 reactive changes를 트리거 할 수 있다.reactive variable
의 값을 변경할 때마다, 해당 reactive variable를 의존하는 쿼리들이 refresh되고, 따라서 application의 UI도 업데이트 된다.쿼리에 의존시키기
- 쿼리 요청 시 사용되는 필드들 중 하나라도 graphql의
reactive variable
의 값을 참조하도록read
함수를 정의했다면 쿼리는 해당reactive variable
에 “의존한다”고 표현할 수 있고,
reactive variable
의 값이 바뀔 때마다 이 값을 의존하는 쿼리도 자동으로 refetch 되며,
- 쿼리의 결과값을 사용하는 컴포넌트도 리렌더 시키게 된다.
// reactive variable 선언 export const todosVar: ReactiveVar<Todos> = makeVar<Todos>(todosInitialValue); // cache에 read 함수 정의 export const cache: InMemoryCache = new InMemoryCache({ typePolicies: { Query: { fields: { todos: { read() { return todosVar(); }, }, }, }, }, }); // query에 reactive variable 의존시키기 export const GET_ALL_TODOS = gql` query GetAllTodos { todos @client { // apollo client의 cache에 명시한 todos field에 대한 read() 함수를 이용하겠다는 의미 id text completed } } `
useReactiveVar
(localState로 사용하기)
- Local Only fields 공식문서 : https://www.apollographql.com/docs/react/local-state/managing-state-with-field-policies/#storing-local-state-in-reactive-variables
useReactiveVar
hook을 사용하면 별도로 쿼리로 래핑하지 않고도, React 컴포넌트에 다이렉트로 컴포넌트의 state로 reactive variable
의 값을 포함시킬 수 있다.reactive variable
의 값을 컴포넌트의 state로 쓰게 되므로, 값이 업데이트 되면 컴포넌트도 리렌더링 된다.