CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tarojs--taro-rn

React Native implementation layer for the Taro cross-platform framework, providing React Native-specific APIs and utilities.

Pending
Overview
Eval results
Files

hooks.mddocs/

React Hooks

Lifecycle and state management hooks for React components in Taro applications, providing seamless integration with React Native lifecycle events.

Capabilities

Page Lifecycle Hooks

React hooks that integrate with Taro's page lifecycle events.

/**
 * Hook that triggers when page is shown
 * @param callback Function to execute when page shows
 */
function useDidShow(callback: () => void): void;

/**
 * Hook that triggers when page is hidden
 * @param callback Function to execute when page hides
 */
function useDidHide(callback: () => void): void;

/**
 * Hook that triggers when page loads
 * @param callback Function to execute when page loads
 */
function useLoad(callback: () => void): void;

/**
 * Hook that triggers when page is ready
 * @param callback Function to execute when page is ready
 */
function useReady(callback: () => void): void;

/**
 * Hook that triggers when page unloads
 * @param callback Function to execute when page unloads
 */
function useUnload(callback: () => void): void;

Usage Examples:

import React, { useState } from 'react';
import { useDidShow, useDidHide, useLoad, useReady, useUnload } from "@tarojs/taro-rn";

function MyPage() {
  const [data, setData] = useState(null);
  const [isVisible, setIsVisible] = useState(true);

  useLoad(() => {
    console.log('Page loaded - initial setup');
    // Initialize page data
  });

  useReady(() => {
    console.log('Page ready - DOM is available');
    // Perform DOM operations if needed
  });

  useDidShow(() => {
    console.log('Page shown - refresh data');
    setIsVisible(true);
    
    // Refresh data when page becomes visible
    fetchLatestData();
  });

  useDidHide(() => {
    console.log('Page hidden - pause operations');
    setIsVisible(false);
    
    // Pause expensive operations
    pauseAnimations();
  });

  useUnload(() => {
    console.log('Page unloading - cleanup');
    
    // Cleanup resources
    clearTimers();
    saveUserProgress();
  });

  return (
    <View>
      <Text>Page is {isVisible ? 'visible' : 'hidden'}</Text>
    </View>
  );
}

App Lifecycle Hooks

Hooks for application-level lifecycle events.

/**
 * Hook that triggers when app launches
 * @param callback Function to execute when app launches, receives launch options
 */
function useLaunch(callback: (options: {
  path: string;
  query: Record<string, any>;
  scene: number;
  shareTicket: string;
  referrerInfo: any;
}) => void): void;

/**
 * Hook that triggers when page is not found
 * @param callback Function to execute when page not found
 */
function usePageNotFound(callback: (res: {
  path: string;
  query: Record<string, any>;
  isEntryPage: boolean;
}) => void): void;

Usage Examples:

import { useLaunch, usePageNotFound } from "@tarojs/taro-rn";

function App() {
  useLaunch((options) => {
    console.log('App launched with path:', options.path);
    console.log('Launch query:', options.query);
    console.log('Launch scene:', options.scene);
    
    // Initialize app based on launch parameters
    if (options.query.userId) {
      initializeUserSession(options.query.userId);
    }
    
    // Track app launch
    analytics.track('app_launch', {
      path: options.path,
      scene: options.scene
    });
  });

  usePageNotFound((res) => {
    console.log('Page not found:', res.path);
    
    // Redirect to error page or home
    Taro.redirectTo({
      url: '/pages/error/index?type=404&path=' + encodeURIComponent(res.path)
    });
  });

  return <AppContent />;
}

Page Interaction Hooks

Hooks for page scroll, pull-to-refresh, and other interactions.

/**
 * Hook that triggers on page scroll
 * @param callback Function to execute on page scroll
 */
function usePageScroll(callback: (res: {
  scrollTop: number;
}) => void): void;

/**
 * Hook that triggers when reaching bottom of page
 * @param callback Function to execute when reaching bottom
 */
function useReachBottom(callback: () => void): void;

/**
 * Hook that triggers on pull-down refresh
 * @param callback Function to execute on pull-down refresh
 */
function usePullDownRefresh(callback: () => void): void;

/**
 * Hook that triggers on window resize
 * @param callback Function to execute on window resize
 */
function useResize(callback: (res: {
  size: {
    windowWidth: number;
    windowHeight: number;
  };
}) => void): void;

Usage Examples:

import React, { useState } from 'react';
import { 
  usePageScroll, 
  useReachBottom, 
  usePullDownRefresh,
  useResize,
  stopPullDownRefresh 
} from "@tarojs/taro-rn";

function ScrollablePage() {
  const [scrollTop, setScrollTop] = useState(0);
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);

  usePageScroll((res) => {
    setScrollTop(res.scrollTop);
    
    // Show/hide back-to-top button
    if (res.scrollTop > 200) {
      showBackToTopButton();
    } else {
      hideBackToTopButton();
    }
  });

  useReachBottom(() => {
    if (!loading) {
      console.log('Reached bottom - load more data');
      loadMoreData();
    }
  });

  usePullDownRefresh(() => {
    console.log('Pull down refresh triggered');
    refreshData();
  });

  useResize((res) => {
    console.log('Window resized:', res.size);
    
    // Adapt layout to new size
    adaptLayoutToSize(res.size);
  });

  const refreshData = async () => {
    setLoading(true);
    try {
      const newData = await fetchLatestData();
      setItems(newData);
    } finally {
      setLoading(false);
      stopPullDownRefresh();
    }
  };

  const loadMoreData = async () => {
    setLoading(true);
    try {
      const moreData = await fetchMoreData(items.length);
      setItems([...items, ...moreData]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View>
      <Text>Scroll position: {scrollTop}</Text>
      {items.map((item, index) => (
        <View key={index}>{item.title}</View>
      ))}
      {loading && <Text>Loading...</Text>}
    </View>
  );
}

Navigation Hooks

Hooks for navigation and routing information.

/**
 * Get router information for current page
 * @returns Router information including path and params
 */
function useRouter(): {
  params: Record<string, string>;
  path: string;
};

/**
 * Hook that triggers when tab item is tapped
 * @param callback Function to execute when tab is tapped
 */
function useTabItemTap(callback: (res: {
  index: number;
  pagePath: string;
  text: string;
}) => void): void;

Usage Examples:

import React, { useEffect, useState } from 'react';
import { useRouter, useTabItemTap } from "@tarojs/taro-rn";

function ProductDetailPage() {
  const router = useRouter();
  const [product, setProduct] = useState(null);

  useEffect(() => {
    console.log('Current page path:', router.path);
    console.log('Page params:', router.params);
    
    // Get product ID from URL parameters
    const productId = router.params.id;
    if (productId) {
      loadProduct(productId);
    }
  }, [router.params]);

  const loadProduct = async (id: string) => {
    try {
      const productData = await fetchProduct(id);
      setProduct(productData);
    } catch (error) {
      console.error('Failed to load product:', error);
    }
  };

  return (
    <View>
      <Text>Product ID: {router.params.id}</Text>
      {product && (
        <View>
          <Text>{product.name}</Text>
          <Text>{product.description}</Text>
        </View>
      )}
    </View>
  );
}

function TabBarContainer() {
  useTabItemTap((res) => {
    console.log('Tab tapped:', res.index, res.pagePath);
    
    // Track tab usage
    analytics.track('tab_tap', {
      index: res.index,
      pagePath: res.pagePath,
      text: res.text
    });
    
    // Handle specific tab actions
    if (res.index === 0) {
      // Home tab - refresh data
      refreshHomeData();
    } else if (res.index === 2) {
      // Profile tab - check login status  
      checkLoginStatus();
    }
  });

  return <TabBarContent />;
}

Hook Patterns

Combining Lifecycle Hooks

import React, { useState, useRef } from 'react';
import { 
  useDidShow, 
  useDidHide, 
  useUnload,
  usePageScroll 
} from "@tarojs/taro-rn";

function usePageVisibility() {
  const [isVisible, setIsVisible] = useState(true);
  const [hasBeenVisible, setHasBeenVisible] = useState(false);

  useDidShow(() => {
    setIsVisible(true);
    setHasBeenVisible(true);
  });

  useDidHide(() => {
    setIsVisible(false);
  });

  return { isVisible, hasBeenVisible };
}

function useScrollPosition() {
  const [scrollTop, setScrollTop] = useState(0);
  const [isScrolling, setIsScrolling] = useState(false);
  const scrollTimer = useRef<NodeJS.Timeout>();

  usePageScroll((res) => {
    setScrollTop(res.scrollTop);
    setIsScrolling(true);
    
    // Clear existing timer
    if (scrollTimer.current) {
      clearTimeout(scrollTimer.current);
    }
    
    // Set timer to detect scroll end
    scrollTimer.current = setTimeout(() => {
      setIsScrolling(false);
    }, 150);
  });

  useUnload(() => {
    if (scrollTimer.current) {
      clearTimeout(scrollTimer.current);
    }
  });

  return { scrollTop, isScrolling };
}

// Usage in component
function MyComponent() {
  const { isVisible, hasBeenVisible } = usePageVisibility();
  const { scrollTop, isScrolling } = useScrollPosition();

  return (
    <View>
      <Text>Page visible: {isVisible ? 'Yes' : 'No'}</Text>
      <Text>Has been visible: {hasBeenVisible ? 'Yes' : 'No'}</Text>
      <Text>Scroll position: {scrollTop}</Text>
      <Text>Currently scrolling: {isScrolling ? 'Yes' : 'No'}</Text>
    </View>
  );
}

Resource Management

import { useState, useRef } from 'react';
import { useDidShow, useDidHide, useUnload } from "@tarojs/taro-rn";

function useResourceManager() {
  const [resources, setResources] = useState(new Set());
  const timers = useRef(new Set());
  const intervals = useRef(new Set());

  const addTimer = (timer: NodeJS.Timeout) => {
    timers.current.add(timer);
    return timer;
  };

  const addInterval = (interval: NodeJS.Timeout) => {
    intervals.current.add(interval);
    return interval;
  };

  const cleanup = () => {
    // Clear all timers
    timers.current.forEach(timer => clearTimeout(timer));
    timers.current.clear();
    
    // Clear all intervals
    intervals.current.forEach(interval => clearInterval(interval));
    intervals.current.clear();
    
    // Clear other resources
    resources.forEach(resource => {
      if (typeof resource.cleanup === 'function') {
        resource.cleanup();
      }
    });
    setResources(new Set());
  };

  useDidHide(() => {
    // Pause non-critical operations when page is hidden
    pauseOperations();
  });

  useDidShow(() => {
    // Resume operations when page is shown
    resumeOperations();
  });

  useUnload(() => {
    cleanup();
  });

  return {
    addTimer,
    addInterval,
    addResource: (resource) => setResources(prev => new Set([...prev, resource])),
    cleanup
  };
}

Install with Tessl CLI

npx tessl i tessl/npm-tarojs--taro-rn

docs

device-system.md

file-system.md

hooks.md

index.md

location-sensors.md

media.md

navigation.md

network.md

storage.md

ui-apis.md

tile.json