Generate a boilerplate for a React Native app with Redux Toolkit and TypeScript.
- User
Generate a boilerplate for a React Native app with Redux Toolkit and TypeScript.
Assistant
The user wants a boilerplate for a React Native application. Key requirements:
- React Native: The core framework.
- Redux Toolkit (RTK): For state management.
- TypeScript: For type safety.
I need to provide a clean, modern, and functional structure. This involves:
- Setting up the project (conceptually, using CLI).
- Configuring TypeScript.
- Setting up Redux Toolkit (store, slices, hooks).
- Integrating the store into the root component.
- Providing a usage example.
Step 1: Project Initialization I should mention
npx react-native@latest init MyApp --template react-native-template-typescript. This is the standard way to get a TS setup.Step 2: Dependencies I need to list the necessary packages:
@reduxjs/toolkitreact-redux
Step 3: Folder Structure A common, scalable structure is essential.
src/ components/ redux/ store.ts hooks.ts slices/ exampleSlice.ts screens/ App.tsxStep 4: Redux Implementation Details
- Slice (
exampleSlice.ts): Needs state interface, initial state, reducers, and actions. - Store (
store.ts): Configures the store usingconfigureStore. - Hooks (
hooks.ts): Custom typed hooks (useAppDispatch,useAppSelector) are a best practice in TS + Redux to avoid typing(state: RootState)every time.
Step 5: Integration in App.tsx
- Wrap the root component with
<Provider store={store}>. - Create a small UI component to demonstrate reading state and dispatching actions.
Step 6: Explanation Add comments or a brief guide on how to run it and what each part does.
Refinement:
- Should I use Expo? The prompt didn't specify. Usually, "React Native app" can mean either, but bare workflow allows for deeper native customization, while Expo is faster to start. I'll stick to the React Native CLI (Bare workflow) as it's the "standard" definition, but I'll mention it works similarly for Expo. Actually, providing the specific installation commands for dependencies is crucial.
- Code blocks should be clearly marked as TypeScript.
Drafting the Code:
- Slice:
createSlice,increment,decrement. - Store:
configureStore. - Hooks:
TypedUseSelectorHook. - App: Import
Provider,Countercomponent.
Reviewing the prompt: "Generate a boilerplate". This implies providing the file structure and the code for the essential files, not just a list of commands.
Let's assemble the response.
- Prerequisites/Setup commands:
npx react-native init ...andnpm install .... - Directory Structure: Visual tree.
- Code Files:
src/store.ts: The central store configuration.src/hooks.ts: Typed hooks (crucial for TS).src/features/counterSlice.ts: A sample slice.App.tsx: The root entry point.
- Usage: How to use it in a component.
This looks solid. I will format it clearly. I will assume the user is using React Native CLI for the most generic "pure" boilerplate, but note that dependencies are the same for Expo.
One minor detail: Navigation. The prompt didn't ask for React Navigation. Adding it might overcomplicate the "boilerplate". I will stick strictly to Redux + TS.
Let's write the code mentally first.
store.ts:export const store = configureStore({ reducer: { counter: counterReducer } }).export type RootState = ReturnType<typeof store.getState>.export type AppDispatch = typeof store.dispatch.hooks.ts: Standard copy-paste from Redux docs.counterSlice.ts:name: 'counter',initialState: { value: 0 },reducers: { increment: state => { state.value += 1 } ...}.App.tsx:<Provider store={store}><Counter /></Provider>.
Looks good. I will present this now. Here is a complete, step-by-step boilerplate guide to setting up a React Native application with Redux Toolkit and TypeScript.
I will assume you are starting with a standard React Native CLI or Expo project.
1. Initialize the Project
If you haven't created a project yet, initialize one with the TypeScript template:
Using React Native CLI:
npx react-native@latest init MyReduxApp --template react-native-template-typescriptUsing Expo:
npx create-expo-app MyReduxApp --template typescript2. Install Dependencies
You need to install Redux Toolkit and React-Redux.
# Using npm npm install @reduxjs/toolkit react-redux # OR using Yarn yarn add @reduxjs/toolkit react-redux3. Project Structure
Create a
srcfolder to keep your code organized. The recommended structure is:src/ ├── store/ │ ├── index.ts # Store configuration │ └── hooks.ts # Typed hooks (useDispatch & useSelector) ├── features/ │ └── counter/ │ └── counterSlice.ts # Example Slice (Reducer + Actions) └── App.tsx # Main Entry Point
4. The Code
Here are the specific files you need to implement.
A. Create a Slice (
src/features/counter/counterSlice.ts)A "slice" contains your state logic and reducers for a specific feature.
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; // Define the shape of the state interface CounterState { value: number; } // Define the initial state const initialState: CounterState = { value: 0, }; export const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state) => { // Redux Toolkit allows us to write "mutating" logic in reducers. // It doesn't actually mutate the state because it uses the Immer library. state.value += 1; }, decrement: (state) => { state.value -= 1; }, incrementByAmount: (state, action: PayloadAction<number>) => { state.value += action.payload; }, }, }); // Export actions to be used in components export const { increment, decrement, incrementByAmount } = counterSlice.actions; // Export the reducer to be added to the store export default counterSlice.reducer;B. Configure the Store (
src/store/index.ts)This file combines your reducers and creates the Redux store.
import { configureStore } from '@reduxjs/toolkit'; import counterReducer from '../features/counter/counterSlice'; export const store = configureStore({ reducer: { counter: counterReducer, // Add other reducers here }, }); // Infer the `RootState` and `AppDispatch` types from the store itself export type RootState = ReturnType<typeof store.getState>; export type AppDispatch = typeof store.dispatch;C. Create Typed Hooks (
src/store/hooks.ts)Instead of using plain
useDispatchanduseSelector, we create typed versions to ensure type safety across the app.import { useDispatch, useSelector } from 'react-redux'; import type { RootState, AppDispatch } from './index'; // Use throughout your app instead of plain `useDispatch` and `useSelector` export const useAppDispatch = () => useDispatch<AppDispatch>(); export const useAppSelector = <T>(selector: (state: RootState) => T): T => useSelector(selector);D. Setup the Provider (
App.tsx)Wrap your main component with the Redux
Provider.import React from 'react'; import { SafeAreaView, StyleSheet, Text, View, Button } from 'react-native'; import { Provider } from 'react-redux'; import { store } from './src/store'; import { useAppSelector, useAppDispatch } from './src/store/hooks'; import { decrement, increment } from './src/features/counter/counterSlice'; // The internal component where we use the Redux hooks const CounterComponent = () => { const count = useAppSelector((state) => state.counter.value); const dispatch = useAppDispatch(); return ( <View style={styles.container}> <Text style={styles.text}>Counter Value: {count}</Text> <Button title="Increment" onPress={() => dispatch(increment())} /> <Button title="Decrement" onPress={() => dispatch(decrement())} /> </View> ); }; // The root App component providing the store const App = () => { return ( <Provider store={store}> <SafeAreaView style={styles.container}> <CounterComponent /> </SafeAreaView> </Provider> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, text: { fontSize: 24, marginBottom: 20, }, }); export default App;Summary of Best Practices used here:
configureStore: Simplifies store setup with default middleware.createSlice: Reduces boilerplate by automatically generating action creators and action types.- Typed Hooks: Using
useAppSelectoranduseAppDispatchprevents TypeScript errors when accessing state or dispatching actions. - TypeScript Interfaces: Defined strict shapes for the state (
CounterState) and the Payloads.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.