Create protected routes using react native, react-navigation v5 and redux

Muhammad Haris
3 min readSep 6, 2020

In this article we will learn about how you can make the routes protected in react native application using react-navigation v5 and redux.

It is really important to protect the routes in application in order to prevent the unauthorized user to access that route. In this small application we will expose the routes if user exists in the redux store.

So let’s get started :)

First of all we will create a react native app using react native cli and install our project dependencies using npm,

npx react-native init awesomeapp && cd awesomeapp && npm i redux react-redux axios, also install react-native navigation using docs . https://reactnavigation.org/docs/getting-started

Note : In order to make that command work, make sure you have node installed on your computer.

First of all we will setup redux store,

I usually follow this practice to configure my redux store.

Reducer for redux,

Action for redux,

Let’s write a fake api call for login and store our user in redux store, We will use react-redux hooks for redux operations. (useSelector , useDispatch).

PS. I’m not focusing on UI

Explanation:

On login if the user is returned by the server we will store the user in redux store, dispatch(onLogin(response?.data)) storing the user in store.

Now Let’s jump into protected routes and configure react native navigation,

If the user doesn’t exists stack navigator only return sign up and login screens. On the other hand if the user exists stack navigator return the remaining screens. In this way we can protect our routes in react native application.
Note: useSelector hook give access to redux store.

I hope it will help you :)

PS . Ignore my bad english

--

--