Skip to main content

How to use the usePageState hook in a React Native component

This example demonstrates how to use the usePageState hook from the @appmaker-xyz/core library to manage the state of a modal in a React Native application.

import React from 'react';
import { usePageState } from '@appmaker-xyz/core';
import { Button, Text, View } from 'react-native';

export function Modal(params) {
// Retrieve the current value of the modalVisible state
const modalVisible = usePageState((state) => state.modalVisible);
// Retrieve the setPageState function to update the modalVisible state
const setPageState = usePageState((state) => state.setPageState);

return (
<View>
{/* Conditionally render the modal if it is visible */}
{modalVisible && (
<View>
<Text>Modal</Text>
<Button onPress={() => setPageState({ modalVisible: false })}>
Close
</Button>
</View>
)}
<Button onPress={() => setPageState({ modalVisible: true })}>Open</Button>
</View>
);
}

  • In this example, the usePageState hook is used to retrieve the current value of the modalVisible state and the setPageState function.
  • The modal is conditionally rendered based on the value of modalVisible, and the setPageState function is used to toggle the visibility of the modal when the "Open" and "Close" buttons are pressed.