Managing States using Hooks
Learn how to manage states in React Native using Hooks.
We'll cover the following
React Native provides us with various Hooks to manage states locally and globally. Let’s briefly look at each of these Hooks:
useState
The useState
Hook enables us to manage states locally. It helps us to maintain and track the internal state of functional components. We should use the useState
Hook when we want to track individual values. These values could be integers, strings, booleans, arrays, objects, etc. The useState
Hook only takes one argument, which is the value of the initial state, and returns two items, i.e., the current state value and a function to update the current state value. The useState
Hook is great for state management. However, it becomes a problem when we have to pass down the states from the parent component to deeply nested child components. This makes the code hard to read, manage, and maintain because the props have to pass unnecessarily through various other components to reach the destination component. This is known as prop drilling.
The code below renders a screen with text displaying the current value, along with three buttons. Clicking the “Click to increment” button increases the value by 1, the “Click to decrement” button decreases the value by 1, and the “Click to reset” button sets the value to 0. The updated value is displayed on the screen. The code snippet below shows the useState
Hook in action.
Get hands-on with 1400+ tech skills courses.