How to access the state using Redux RTK in React native app?
In our previous blogs, we have learned to create a simple app with React.js, replacing redux with the help of the react hook, and many other things. Now it's time to move ahead and learn something new. In today’s article, we will access the state using Redux RTK.
To get started, we have to install the Redux Toolkit package. In our previous blogs, we detailed the entire installation process for Redux Toolkit. But, since we want to share complete information with our novice React developers, let's start from scratch.
Step 1: Install the Redux Toolkit package
First of all, we have to install Redux Toolkit and React-redux within the project.
As Redux Toolkit is already installed in the project in Typescript format, we have to install react-Redux using the below command:
React Redux has a dependency on @types/react-redux so the type definition file of the package will be automatically installed with it.
Step 2: Create an API with customBaseQuery
As we are using Redux RTK queries in our React Native project, we can't figure out how to access the state without firing the query each time. So, it is mandatory to create an API with customBaseQuery using the below command.
Step 3: Inject endpoints
The next step after creating APIs is to inject endpoints. You can insert endpoints in your application by the below written command.
Step 4: Configure the Store:
It's quite simple to configure the store in a React native app, and you can do it by following these steps. Initially, you have to create a store folder and then create an index.js file in the store folder. After that, use connect() to link the components to the store and send the actions to the store to change it.
Step 5: Using Dispatch Hook
You can also use the Redux RTK useDispatch hook to send actions that change the state. Here is the command to use useDispatch:
Lastly, we have to make a call to the getUser API through the redux-generated hook whenever the application is opened. This is effective, and we will get the desired response.
Now, we need to access the user data on another screen of our app without calling the API again (Redux should have cached or saved the data).
Final thoughts
In conclusion, Redux RTK is the best tool that can be used to easily access the state of your React Native app. It is a great alternative to building a custom Redux store that can help you keep your codebase cleaner and more organized. With Redux RTK, you can access the state of your React Native app with ease, allowing you to quickly access the data you need.
No comments:
Post a Comment