State Management
Incrementing Number
Suppose we want to build an an app with the following requirements:
A Text component displaying the counter value, with an initial value of 0.
A Button to increment the counter.
Another Button to decrement the counter.
Wrong Example
Without knowledge on React state management, our knowledge of javascript would tell us to do something like this:
React Native doesn’t know when to re-render a component if we simply use let counter = 0 and update it. This breaks the rules for props since it involves mutating the value directly.
Correct Example
Instead, React provides the useState hook to manage state changes and trigger re-renders appropriately.
Managing Text
State is used in various components, such as TextInput, where the text changes every time the user types something. We use useState to track and update the text.
Conditional Rendering
Conditional rendering allows components to render dynamically based on the state. Here’s an example with a modal:
In this example, the toggleModal function toggles the isModalOpen state, which conditionally renders the ModalComponent.
Last updated