Get Started with React Native, Redux and TypeScript
Tags: typescript, redux, reactnative
Published: 2021-09-28 16:40:40

One of the popular state management tools out there is Redux. 

Setting up a Typescript React Native Project with Redux can be tricky for beginners, in this article, I will teach you how you can easily get started.

I am assuming, you have a React Native Typescript Project setup, if you don't, you can run this command:

``npx react-native init ProjectName --template react-native-template-typescript``

Your project will automatically be bootstrapped with typescript template.


#Installing dependencies

I like using yarn, but you can also use npm

`yarn add redux react-redux redux-thunk`

Afterwards, let's install redux type definitions 

``yarn add @types/react-redux -D``

Create a new folder call "Store".
You can name the folder as you desire, but I prefer to use store.
Inside this folder, create three folders:

- actions
- reducers
- types

and lastly, create an index.tsx file.

In your index.tsx file, paste the following code
<pre>
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import appReducer from './reducers';


export default createStore(appReducer, applyMiddleware(thunk));
</pre>

The next action is to define your Types.
In your types folder, create an index.tsx file and paste the following code

<pre>
export const USER_TODO = 'USER_TODO';
</pre>

Save and close.

Next stop is the actions folder, for this folder, I like to create an index.tsx file and other actions. So if you are creating a big application, you might have something like this

``index.tsx
users.tsx
admin.tsx
payment.tsx etc.``

This makes your file structure cleaner and more understandable.

But for this simple application, we will be needing just two files:

``index.tsx and 
todo.tsx``

Inside your index.tsx file, paste the code below:

<pre>
import todoAction from './todo';


export { todoAction };
</pre>

Save and Close

In your todo.tsx file, you will define how your actions are to look like,

First import all your types

<pre>
import { USER_TODO, } from '../types';
</pre>

Then set up your actions
<pre>
const setUserTodo = (payload: number) => ({
  type: USER_TODO,
  payload,
});

export default {
  setUserTodo,
};
</pre>

Save and Close.

Lastly, create two files in your reducers folder 

``index.tsx and 
todo.tsx ```


inside your todo.tsx file, paste the following code:
<pre>
import { USER_TODO } from '../types';

const initialstate = {
    userTodo: [],
};

type Action = {
    type: string,
    payload?: any
}

export default (state: any = initialstate, action: Action) => {
    switch (action.type) {
        case USER_TODO:
            return Object.assign({}, state, {
                userTodo: action.payload,
            });
        default:
            return state;
    }
};
</pre>

inside your index.tsx file, paste the following code:

<pre>
import { combineReducers } from 'redux';
import todo from './todo';


const appReducer = combineReducers({
    todo,
});

export default appReducer;

export type State = ReturnType<typeof appReducer>
</pre>

And that's it! You have successfully set up your redux store, now let's head over to the UI part.

I will make use of JSON public placeholder API to generate list of todos

```https://jsonplaceholder.typicode.com/todos/```

You can use the ``useDispatch`` hooks from react-redux to easily dispatch data into your reducers

In your App.tsx, paste the following code:

<pre>
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { useDispatch } from 'react-redux';
import { todoAction } from '../store/actions';

interface AppProps {
  navigation: any;
  setTodo: any;
}

const Welcome: React.FC<AppProps> = ({ navigation: { navigate } }) => {
  const dispatch = useDispatch();

  React.useEffect(() => {
    loadTodos();
  }, []);

  const loadTrivia = () => {
     try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/todos/'
    );
    const json = await response.json();
     dispatch(todoAction.setUserTodo(json));
  } catch (error) {
    console.error(error);
  }
  };

  return (
    < View style={styles.container}>
      
    < /View>
  );
};

export default App;

</pre>

And to get the list of these todo, use ``useSelector`` hooks from react-redux

<pre>
import React from 'react';
import { View, Text } from 'react-native';
import { useSelector } from 'react-redux';

interface TodoProps {
  navigation: any;
}

const Todo = (props: TodoProps) => {
  const { userTodo } = useSelector((state: State) => state.todo);

const TodoList = ({data}) => {
      return (
            < View>
             < Text>{data.title} < /Text>
            < /View>
      )};

  return (
      < FlatList
        data={userTodo}
        renderItem={({ item }) => <TodoList {...item} />} />
  )};

export default Todo;
</pre>


And that is it!

That is the simple way to easily add redux to your React Native Typescript project.

Let me know if you have any questions!