There are currently countless numbers of state management libraries out there. This blog will show you how to use state management for React Native in Nx monorepo with TanStack Query (which happens to use Nx on their repo) and Redux.
This blog will show:
- How to set up these libraries and their dev tools
- How to build the sample page below in React Native / Expo with state management
- How to do unit testing
It will call an API and show a cat fact on the page, allowing users to like or dislike the data.
Github repo: https://github.com/xiongemi/nx-expo-monorepo
Before We Start
From TanStack Query documentation, it says:
- TanStack Query is a server-state library.
- Redux is a client-state library.
What is the difference between the server state and the client state?
In short:
- Calling an API, dealing with asynchronous data-> server state
- Everything else about UI, dealing with synchronous data -> client state
Installation
To use TanStack Query / React Query for the server state, I need to install:
- Library: @tanstack/react-query
- Dev tools: @tanstack/react-query-devtools
I will use Redux for everything else.
- Library: redux, react-redux, @reduxjs/toolkit
- Dev tools: @redux-devtools/extension
- Logger: redux-logger, @types/redux-logger
- Storage: redux-persist, @react-native-async-storage/async-storage
To install all the above packages:
❯
#npm
❯
npm install @tanstack/react-query @tanstack/react-query-devtools redux react-redux @reduxjs/toolkit @redux-devtools/extension redux-logger @types/redux-logger redux-persist @react-native-async-storage/async-storage --save-dev
❯
#yarn
❯
yarn add @tanstack/react-query @tanstack/react-query-devtools redux react-redux @reduxjs/toolkit @redux-devtools/extension redux-logger @types/redux-logger redux-persist @react-native-async-storage/async-storage --dev
❯
#pnpm
❯
pnpm add @tanstack/react-query @tanstack/react-query-devtools redux react-redux @reduxjs/toolkit @redux-devtools/extension redux-logger @types/redux-logger redux-persist @react-native-async-storage/async-storage --save-dev
Server State with React Query
Setup Devtools
First, you need to add React Query / TanStack Query in the App.tsx
:
1import React from 'react';
2import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
3import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
4import { Platform } from 'react-native';
5
6const App = () => {
7 const queryClient = new QueryClient();
8 return (
9 <QueryClientProvider client={queryClient}>
10 {Platform.OS === 'web' && <ReactQueryDevtools />}
11 ...
12 </QueryClientProvider>
13 );
14};
15
16export default App;
17
Note: the React Query Devtools currently do not support react native, and it only works on the web, so there is a condition: { Platform.OS === ‘web’ && <ReactQueryDevtools />}.
For the react native apps, in order to use this tool, you need to use react-native-web to interpolate your native app to the web app first.
If you open my Expo app on the web by running nx start cats
and choose the options Press w │ open web
, you should be able to use the dev tools and see the state of my react queries:
Or you can run npx nx serve cats
to launch the app in a web browser and debug from there.
Create a Query
What is a query?
“A query is a declarative dependency on an asynchronous source of data that is tied to a unique key. A query can be used with any Promise-based method (including GET and POST methods) to fetch data from a server.” (https://tanstack.com/query/v4/docs/react/guides/queries)
Now let’s add our first query. In this example, it will be added under lib/queries
folder. To create a query to fetch a new fact about cats, run the command:
❯
# expo workspace
❯
npx nx generate @nx/expo:lib libs/queries/use-cat-fact
❯
# react-native workspace
❯
npx nx generate @nx/react-native:lib libs/queries/use-cat-fact
Or use Nx Console:
Now notice under libs folder, use-cat-fact
folder got created under libs/queries
:
If you use React Native CLI, just add a folder in your workspace root.
For this app, let’s use this API: https://catfact.ninja/. At libs/queries/use-cat-fact/src/lib/use-cat-fact.ts
, add code to fetch the data from this API:
1import { useQuery } from '@tanstack/react-query';
2
3export const fetchCatFact = async (): Promise<string> => {
4 const response = await fetch('https://catfact.ninja/fact');
5 const data = await response.json();
6 return data.fact;
7};
8
9export const useCatFact = () => {
10 return useQuery({
11 queryKey: ['cat-fact'],
12 queryFn: fetchCatFact,
13 enabled: false,
14 });
15};
16
Essentially, you have created a custom hook that calls useQuery function from the TanStack Query library.
Unit Testing
If you render this hook directly and run the unit test with the command npx nx test queries-use-cat-fact
, this error will show up in the console:
❯
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
❯
1. You might have mismatching versions of React and the renderer (such as React DOM)
❯
2. You might be breaking the Rules of Hooks
❯
3. You might have more than one copy of React in the same app
❯
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
To solve this, you need to wrap your component inside the renderHook function from @testing-library/react-native
library:
1. Install Library to Mock Fetch
Depending on which library you use to make HTTP requests. (e.g. fetch, axios), you need to install a library to mock the response.
- If you use
fetch
to fetch data, you need to installjest*fetch-mock
. - If you use
axios
to fetch data, you need to installaxio*-mock-adapter
.
For this example, since it uses fetch
, you need to install jest-fetch-mock
:
❯
#npm
❯
npm install jest-fetch-mock --save-dev
❯
#yarn
❯
yard add jest-fetch-mock --dev
You also need to mock fetch
library in libs/queries/use-cat-fact/test-setup.ts
:
1import fetchMock from 'jest-fetch-mock';
2
3fetchMock.enableMocks();
4
2. Create Mock Query Provider
In order to test out useQuery
hook, you need to wrap it inside a mock QueryClientProvider
. Since this mock query provider is going to be used more than once, let’s create a library for this wrapper:
❯
# expo library
❯
npx nx generate @nx/expo:library libs/queries/test-wrapper
❯
# react native library
❯
npx nx generate @nx/react-native:library libs/queries/test-wrapper
Then a component inside this library:
❯
# expo library
❯
npx nx generate @nx/expo:component libs/queries/test-wrapper/src/lib/test-wrapper/test-wrapper
❯
# react native library
❯
npx nx generate @nx/react-native:component libs/queries/test-wrapper/src/lib/test-wrapper/test-wrapper
Add the mock QueryClientProvider
in libs/queries/test-wrapper/src/lib/test-wrapper/test-wrapper.tsx
:
1import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
2import React from 'react';
3
4export interface TestWrapperProps {
5 children: React.ReactNode;
6}
7
8export function TestWrapper({ children }: TestWrapperProps) {
9 const queryClient = new QueryClient();
10 return (
11 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
12 );
13}
14
15export default TestWrapper;
16
3. Use Mock Responses in Unit Test
Then this is what the unit test for my query would look like:
1import { TestWrapper } from '@nx-expo-monorepo/queries/test-wrapper';
2import { renderHook, waitFor } from '@testing-library/react-native';
3import { useCatFact } from './use-cat-fact';
4import fetchMock from 'jest-fetch-mock';
5
6describe('useCatFact', () => {
7 afterEach(() => {
8 jest.resetAllMocks();
9 });
10
11 it('status should be success', async () => {
12 // simulating a server response
13 fetchMock.mockResponseOnce(
14 JSON.stringify({
15 fact: 'random cat fact',
16 })
17 );
18
19 const { result } = renderHook(() => useCatFact(), {
20 wrapper: TestWrapper,
21 });
22 result.current.refetch(); // refetching the query
23 expect(result.current.isLoading).toBeTruthy();
24
25 await waitFor(() => expect(result.current.isLoading).toBe(false));
26 expect(result.current.isSuccess).toBe(true);
27 expect(result.current.data).toEqual('random cat fact');
28 });
29
30 it('status should be error', async () => {
31 fetchMock.mockRejectOnce();
32
33 const { result } = renderHook(() => useCatFact(), {
34 wrapper: TestWrapper,
35 });
36 result.current.refetch(); // refetching the query
37 expect(result.current.isLoading).toBeTruthy();
38
39 await waitFor(() => expect(result.current.isLoading).toBe(false));
40 expect(result.current.isError).toBe(true);
41 });
42});
43
If you use axios
, your unit test would look like this:
1// If you use axios, your unit test would look like this:
2import { TestWrapper } from '@nx-expo-monorepo/queries/test-wrapper';
3import { renderHook, waitFor } from '@testing-library/react-native';
4import { useCatFact } from './use-cat-fact';
5import axios from 'axios';
6import MockAdapter from 'axios-mock-adapter';
7
8// This sets the mock adapter on the default instance
9const mockAxios = new MockAdapter(axios);
10
11describe('useCatFact', () => {
12 afterEach(() => {
13 mockAxios.reset();
14 });
15
16 it('status should be success', async () => {
17 // simulating a server response
18 mockAxios.onGet().replyOnce(200, {
19 fact: 'random cat fact',
20 });
21
22 const { result } = renderHook(() => useCatFact(), {
23 wrapper: TestWrapper,
24 });
25 result.current.refetch(); // refetching the query
26 expect(result.current.isLoading).toBeTruthy();
27
28 await waitFor(() => expect(result.current.isLoading).toBe(false));
29 expect(result.current.isSuccess).toBe(true);
30 expect(result.current.data).toEqual('random cat fact');
31 });
32
33 it('status should be error', async () => {
34 mockAxios.onGet().replyOnce(500);
35
36 const { result } = renderHook(() => useCatFact(), {
37 wrapper: TestWrapper,
38 });
39 result.current.refetch(); // refetching the query
40 expect(result.current.isLoading).toBeTruthy();
41
42 await waitFor(() => expect(result.current.isLoading).toBe(false));
43 expect(result.current.isError).toBe(true);
44 });
45});
46
Notice that this file imports TestWrapper
from @nx-expo-monorepo/queries/test-wrapper
, and it is added to renderHook
function with { wrapper: TestWrapper }
.
Now you run the test command nx test queries-use-cat-fact
, it should pass:
❯
PASS queries-use-cat-fact libs/queries/use-cat-fact/src/lib/use-cat-fact.spec.ts (5.158 s)
❯
useCatFact
❯
✓ status should be success (44 ms)
❯
✓ status should be error (96 ms)
Integrate with Component
Currently userQuery
returns the following properties:
isLoading
orstatus === 'loading'
- The query has no data yetisError
orstatus === 'error'
- The query encountered an errorisSuccess
orstatus === 'success'
- The query was successful and data is available
Now with components controlled by the server state, you can leverage the above properties and change your component to follow the below pattern:
1export interface CarouselProps {
2 isError: boolean;
3 isLoading: boolean;
4 isSuccess: boolean;
5}
6
7
8export function Carousel({
9 isSuccess,
10 isError,
11 isLoading,
12}: CarouselProps) {
13 return (
14 <>
15 {isSuccess && (
16 ...
17 )}
18 {isLoading && (
19 ...
20 )}
21 {isError && (
22 ...
23 )}
24 </>
25 );
26}
27
28export default Carousel;
29
Then in the parent component, you can use the query created above:
1import { useCatFact } from '@nx-expo-monorepo/queries/use-cat-fact';
2import { Carousel } from '@nx-expo-monorepo/ui';
3import React from 'react';
4
5export function Facts() {
6 const { data, isLoading, isSuccess, isError, refetch, isFetching } =
7 useCatFact();
8
9 return (
10 <Carousel
11 content={data}
12 isLoading={isLoading || isFetching}
13 isSuccess={isSuccess}
14 isError={isError}
15 onReload={refetch}
16 >
17 ...
18 );
19}
20
If you serve the app on the web and open the React Query Devtools, you should be able to see the query I created cat-fact
and data in the query.
Redux
Create a Library
First, you need to create a library for redux:
❯
# expo library
❯
npx nx generate @nx/expo:lib libs/states/cat
❯
# react native library
❯
npx nx generate @nx/react-native:lib libs/states/cat
This should create a folder under libs:
Create a State
For this app, it is going to track when users click the like button, so you need to create a state called likes
.
You can use the Nx Console to create a redux slice:
Or run this command:
❯
npx nx generate @nx/react:redux libs/states/cat/src/lib/likes/likes
Then update the redux slice at libs/states/cat/src/lib/likes/likes.slice.ts
:
1import {
2 createEntityAdapter,
3 createSelector,
4 createSlice,
5 EntityState,
6} from '@reduxjs/toolkit';
7
8export const LIKES_FEATURE_KEY = 'likes';
9
10export interface LikesEntity {
11 id: string;
12 content: string;
13 dateAdded: number;
14}
15
16export type LikesState = EntityState<LikesEntity>;
17
18export const likesAdapter = createEntityAdapter<LikesEntity>();
19
20export const initialLikesState: LikesState = likesAdapter.getInitialState();
21
22export const likesSlice = createSlice({
23 name: LIKES_FEATURE_KEY,
24 initialState: initialLikesState,
25 reducers: {
26 like: likesAdapter.addOne,
27 remove: likesAdapter.removeOne,
28 clear: likesAdapter.removeAll,
29 },
30});
31
32/*
33 * Export reducer for store configuration.
34 */
35export const likesReducer = likesSlice.reducer;
36
37export const likesActions = likesSlice.actions;
38
39const { selectAll } = likesAdapter.getSelectors();
40
41const getlikesState = <ROOT extends { likes: LikesState }>(
42 rootState: ROOT
43): LikesState => rootState[LIKES_FEATURE_KEY];
44
45const selectAllLikes = createSelector(getlikesState, selectAll);
46
47export const likesSelectors = {
48 selectAllLikes,
49};
50
Every time the “like” button gets clicked, you want to store the content of what users liked. So you need to create an entity to store this information.
1export interface LikesEntity {
2 id: string;
3 content: string;
4 dateAdded: number;
5}
6
This state has 3 actions:
- like: when users click like
- remove: when users cancel the like
- clear: when users clear all the likes
Root Store
Then you have to add the root store and create a transform function to stringify the redux state:
1import { EntityState } from '@reduxjs/toolkit';
2import { createTransform } from 'redux-persist';
3import { LIKES_FEATURE_KEY } from '../likes/likes.slice';
4
5const transformEntityStateToPersist = createTransform(
6 // transform state on its way to being serialized and persisted.
7 (
8 entityState: EntityState<any>
9 ): {
10 ids: string;
11 entities: any;
12 } => {
13 return {
14 ...entityState,
15 ids: JSON.stringify(entityState.ids),
16 entities: JSON.stringify(entityState.entities),
17 };
18 },
19 // transform state being rehydrated
20 (entityState: { ids: string; entities: string }): EntityState<any> => {
21 return {
22 ...entityState,
23 ids: JSON.parse(entityState.ids),
24 entities: JSON.parse(entityState.entities),
25 };
26 },
27 // define which reducers this transform gets called for.
28 { whitelist: [LIKES_FEATURE_KEY] }
29);
30
31export { transformEntityStateToPersist };
32
1import { initialLikesState } from '../likes/likes.slice';
2
3import { RootState } from './root-state.interface';
4
5export const initialRootState: RootState = {
6 likes: initialLikesState,
7};
8
1import { LikesState } from '../likes/likes.slice';
2
3export interface RootState {
4 likes: LikesState;
5}
6
1import { combineReducers } from '@reduxjs/toolkit';
2
3import { likesReducer } from '../likes/likes.slice';
4import { RootState } from './root-state.interface';
5
6export const createRootReducer = combineReducers<RootState>({
7 likes: likesReducer,
8});
9
1import { configureStore } from '@reduxjs/toolkit';
2import logger from 'redux-logger';
3import { persistStore, persistReducer, PersistConfig } from 'redux-persist';
4
5import { initialRootState } from './root-state.initial';
6import { RootState } from './root-state.interface';
7import { createRootReducer } from './root.reducer';
8
9declare const process: any;
10
11export const createRootStore = (persistConfig: PersistConfig<RootState>) => {
12 const isDevelopment = process.env.NODE_ENV === 'development';
13
14 const rootReducer = createRootReducer;
15 const persistedReducer = persistReducer(persistConfig, rootReducer);
16
17 const store = configureStore({
18 reducer: persistedReducer,
19 middleware: (getDefaultMiddleware) => {
20 const defaultMiddleware = getDefaultMiddleware({
21 serializableCheck: false,
22 });
23 return isDevelopment
24 ? defaultMiddleware.concat(logger)
25 : defaultMiddleware;
26 },
27 devTools: isDevelopment,
28 preloadedState: initialRootState,
29 });
30
31 const persistor = persistStore(store);
32
33 return { store, persistor };
34};
35
Connect Redux State with UI
Then in apps/cats/src/app/App.tsx
, you have to:
- wrap the app inside the
StoreProvider
with the root store to connect with the Redux state. - wrap the app inside
PersistGate
to persist the redux state in the storage
1import React from 'react';
2import AsyncStorage from '@react-native-async-storage/async-storage';
3import { PersistGate } from 'redux-persist/integration/react';
4import {
5 createRootStore,
6 transformEntityStateToPersist,
7} from '@nx-expo-monorepo/states/cat';
8import { Loading } from '@nx-expo-monorepo/ui';
9import { Provider as StoreProvider } from 'react-redux';
10
11const App = () => {
12 const persistConfig = {
13 key: 'root',
14 storage: AsyncStorage,
15 transforms: [transformEntityStateToPersist],
16 };
17 const { store, persistor } = createRootStore(persistConfig);
18
19 return (
20 <PersistGate loading={<Loading />} persistor={persistor}>
21 <StoreProvider store={store}>...</StoreProvider>
22 </PersistGate>
23 );
24};
25
26export default App;
27
In your component where the like button is located, you need to dispatch the like action. I created a file at apps/cats/src/app/facts/facts.props.ts
:
1import {
2 likesActions,
3 LikesEntity,
4 RootState,
5} from '@nx-expo-monorepo/states/cat';
6import { AnyAction, ThunkDispatch } from '@reduxjs/toolkit';
7
8const mapDispatchToProps = (
9 dispatch: ThunkDispatch<RootState, void, AnyAction>
10) => {
11 return {
12 like(item: LikesEntity) {
13 dispatch(likesActions.like(item));
14 },
15 };
16};
17
18type mapDispatchToPropsType = ReturnType<typeof mapDispatchToProps>;
19
20type FactsProps = mapDispatchToPropsType;
21
22export { mapDispatchToProps };
23export type { FactsProps };
24
Now you have passed the like
function to the props of the facts component. Now inside the facts component, you can call the like function from props to dispatch the like action.
Debugging
To debug redux with Expo, I can simply open the Debugger Menu by entering “d” in the console or in the app, then choose the option “Open JS Debugger”.
Then you can view my redux logs in the JS Debugger console:
Or you can run npx nx serve cats
to launch the app in web view. Then you can use Redux Devtools and debug the native app like a web app:
Summary
Here is a simple app that uses TanStack Query and Redux for state management. These 2 tools are pretty powerful and they manage both server and client state for you, which is easy to scale, test, and debug.
Nx is a powerful monorepo tool. Together with Nx and these 2 state management tools, it will be very easy to scale up any app.
- TanStack Query site: https://tanstack.com/query/latest
- Official @nx/expo plugin: /nx-api/expo
- Official @nx/react-native plugin: /nx-api/react-native