Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging Face Frontier Reasoning Traces

Generate a boilerplate for a React Native app with Redux Toolkit and TypeScript.

  1. User

    Generate a boilerplate for a React Native app with Redux Toolkit and TypeScript.

  2. Gemini Assistant

    Comprehending the Requirements

    I'm now zeroing in on the specifications. It's a React Native app using Redux Toolkit and TypeScript, and the objective is to produce a boilerplate. I'm focusing on distilling the core necessities to kickstart the project efficiently. The framework is rapidly becoming clear.

    Prioritizing Dependencies

    I've moved on to the core requirements. I'm listing all the essential dependencies, confirming react-redux and @reduxjs/toolkit are non-negotiable. The boilerplate's structure demands a carefully crafted store.ts file, and typed hooks, like useAppDispatch and useAppSelector, will be integral. I am now refining the exact implementation steps.

    Mapping the Blueprint

    I'm now outlining the steps for generating the boilerplate. First, I'm thinking through the fundamental structure, including the initial commands: react-native init followed by installing the key dependencies. The folder structure, src/app, src/features, and src/components, is taking shape to house Redux and app components, respectively.

    Deconstructing the Solution

    I'm presently breaking down the user request into manageable phases. First, grasping the intent: produce a ready-to-use template for a React Native application that leverages Redux Toolkit and TypeScript. The plan is to go with a straightforward structure. I'm focusing on the precise steps to achieve a solid initial configuration.

    \n\n

    Architecting the Implementation

    I'm now fully immersed in the creation process. The structure is taking shape, and the crucial file contents are being outlined step by step. I'm focusing on the React Native initialization command and folder structure, then setting up the Redux store, and providing example components, like slices and hooks, complete with detailed explanations. I'm also preparing to add a section about further steps, like navigation.

    Here is a complete, production-ready boilerplate guide for setting up a React Native app with Redux Toolkit and TypeScript.

    This guide assumes you have your environment set up for React Native development.

    1. Initialization & Installation

    First, create a new React Native project (if you haven't already) and install the necessary dependencies.

    # 1. Create the project (Select TypeScript when asked, or it is default in new versions)
    npx react-native@latest init MyApp
    
    # 2. Navigate into project
    cd MyApp
    
    # 3. Install Redux Toolkit and React-Redux
    npm install @reduxjs/toolkit react-redux
    # OR
    yarn add @reduxjs/toolkit react-redux
    

    2. Recommended Folder Structure

    Organizing by "features" is the recommended standard for Redux Toolkit.

    MyApp/
    ├── src/
    │   ├── app/
    │   │   ├── hooks.ts       <-- Typed Redux hooks
    │   │   └── store.ts       <-- Store configuration
    │   ├── components/        <-- Shared UI components
    │   └── features/
    │       └── counter/       <-- Example Feature
    │           ├── counterSlice.ts
    │           └── Counter.tsx
    ├── App.tsx
    └── index.js
    

    3. The Setup Code

    Here is the code for each file in the structure above.

    A. Store Configuration

    File: src/app/store.ts

    This creates the Redux store and infers the types for TypeScript.

    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;
    

    B. Typed Hooks

    File: src/app/hooks.ts

    While you can use useDispatch and useSelector directly, using these typed versions is best practice in TypeScript to avoid constantly re-typing state in every component.

    import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
    import type { RootState, AppDispatch } from './store';
    
    // Use throughout your app instead of plain `useDispatch` and `useSelector`
    export const useAppDispatch: () => AppDispatch = useDispatch;
    export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
    

    C. Create a Slice (Example Feature)

    File: src/features/counter/counterSlice.ts

    A "slice" contains the logic (actions and reducers) for a specific feature.

    import { createSlice, PayloadAction } from '@reduxjs/toolkit';
    import type { RootState } from '../../app/store';
    
    // Define a type for the slice state
    interface CounterState {
      value: number;
    }
    
    // Define the initial state using that type
    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 const { increment, decrement, incrementByAmount } = counterSlice.actions;
    
    // Selector to get the count value directly
    export const selectCount = (state: RootState) => state.counter.value;
    
    export default counterSlice.reducer;
    

    D. The UI Component

    File: src/features/counter/Counter.tsx

    This component connects to the store using our custom hooks.

    import React, { useState } from 'react';
    import { View, Text, Button, StyleSheet, TextInput } from 'react-native';
    import { useAppSelector, useAppDispatch } from '../../app/hooks';
    import { increment, decrement, incrementByAmount, selectCount } from './counterSlice';
    
    export function Counter() {
      const count = useAppSelector(selectCount);
      const dispatch = useAppDispatch();
      const [incrementAmount, setIncrementAmount] = useState('2');
    
      const incrementValue = Number(incrementAmount) || 0;
    
      return (
        <View style={styles.container}>
          <Text style={styles.title}>Redux Toolkit Quick Start</Text>
          
          <View style={styles.row}>
            <Button title="-" onPress={() => dispatch(decrement())} />
            <Text style={styles.value}>{count}</Text>
            <Button title="+" onPress={() => dispatch(increment())} />
          </View>
    
          <View style={styles.inputRow}>
            <TextInput
              style={styles.input}
              value={incrementAmount}
              onChangeText={setIncrementAmount}
              keyboardType="numeric"
            />
            <Button
              title="Add Amount"
              onPress={() => dispatch(incrementByAmount(incrementValue))}
            />
          </View>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 20,
      },
      title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
      },
      row: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 20,
      },
      value: {
        fontSize: 30,
        marginHorizontal: 20,
      },
      inputRow: {
        flexDirection: 'column',
        alignItems: 'center',
        gap: 10,
      },
      input: {
        fontSize: 18,
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 4,
        padding: 8,
        width: 60,
        marginBottom: 10,
        textAlign: 'center',
      },
    });
    

    E. Integrate Provider in Root App

    File: App.tsx

    Wrap your main application with the Redux Provider.

    import React from 'react';
    import { SafeAreaView, StatusBar, StyleSheet } from 'react-native';
    import { Provider } from 'react-redux';
    import { store } from './src/app/store';
    import { Counter } from './src/features/counter/Counter';
    
    function App(): React.JSX.Element {
      return (
        <Provider store={store}>
          <SafeAreaView style={styles.container}>
            <StatusBar barStyle="dark-content" />
            <Counter />
          </SafeAreaView>
        </Provider>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        backgroundColor: '#f5f5f5',
      },
    });
    
    export default App;
    

    4. How to Run

    1. Save all files in the structure provided.
    2. Run your Metro bundler and simulator:
    # iOS
    npm run ios
    
    # Android
    npm run android
    

    Optional: Boilerplate Extensions

    If you want to expand this boilerplate for a real-world app, consider adding:

    1. Redux Persist: To save the state to AsyncStorage so data remains when the app is closed.
      • npm install redux-persist @react-native-async-storage/async-storage
    2. Async Thunks: For API calls. Redux Toolkit has createAsyncThunk built-in.
    3. React Navigation: Standard for routing screens setup inside the App.tsx file.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.