NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Incrementing Number
  • Wrong Example
  • Correct Example
  • Managing Text
  • Conditional Rendering
Edit on GitHub
Export as PDF
  1. Orbital
  2. React Native

State Management

Incrementing Number

Suppose we want to build an an app with the following requirements:

  1. A Text component displaying the counter value, with an initial value of 0.

  2. A Button to increment the counter.

  3. 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:

function Component() {
  let counter = 0;
  
  // DON'T DO THIS - mutating counter doesn't tell React to re-render
  return <Button onPress={() => counter += 1} />;
}

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.

function Component() {
  const [counter, setCounter] = useState(0);
  
  // This is correct - the counter value is updated in the next render
  return <Button onPress={() => setCounter(counter + 1)} />;
}

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.

import React, { useState } from 'react';
import { View, TextInput } from 'react-native';

const TextInputComponent = () => {
  const [text, setText] = useState('');

  return (
    <View>
      <TextInput 
        style={styles.input} 
        value={text} 
        onChangeText={setText} 
        placeholder="Type here"
      />
    </View>
  );
};

Conditional Rendering

Conditional rendering allows components to render dynamically based on the state. Here’s an example with a modal:

import React, { useState } from 'react';
import { View, Button, Modal, Text } from 'react-native';

const ModalComponent = () => (
  <View>
    <Text>This is a modal!</Text>
  </View>
);

const App = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const toggleModal = () => {
    setIsModalOpen(!isModalOpen);
  };

  return (
    <View >
      <Button title="Toggle Modal" onPress={toggleModal} />
      {isModalOpen && (
        <Modal
          transparent={true}
          visible={isModalOpen}
          onRequestClose={toggleModal}
        >
          <View>
            <ModalComponent />
            <Button title="Close Modal" onPress={toggleModal} />
          </View>
        </Modal>
      )}
    </View>
  );
};

In this example, the toggleModal function toggles the isModalOpen state, which conditionally renders the ModalComponent.

PreviousPropsNextGit

Last updated 12 months ago