skip to Main Content

My react-native seems to be very slow after I added the 2 useEffects to get data from my sqlite database. It makes the app so slow that it barely responds to user inputs. How can I resolve this issue?

import { SafeAreaView } from "react-native-safe-area-context";
import { Pressable, View } from "react-native";

import { Header, AddMeal, TabBar, Rings4, RecentMeals } from "../components";

import { COLORS } from "../constants/colors";
import DraggableFlatList, { ScaleDecorator } from "react-native-draggable-flatlist";
import {  useEffect, useState } from "react";

import * as SQLite from "expo-sqlite";

const widgetsEnum = {
  "rings4": 0,
  "recentmeals": 1,
}

const App = () => {
  function getWidget(type){
    switch(type){
      case 0: return(<Rings4 macros={macros} />);
      case 1: return(<RecentMeals />);
    }
    return(<></>);
  }

const renderItem = ({item, drag, isActive}) => {
  return (
    <ScaleDecorator
      activeScale={1.05}
    >
      <Pressable
        onLongPress={drag}
        disabled={isActive}
      >
        { getWidget(item.type) }
      </Pressable>
    </ScaleDecorator>
  )
}

  const [widgets, setWidgets] = useState(
    [
      {type: widgetsEnum.rings4, id: 1}, 
      {type: widgetsEnum.recentmeals, id: 2}, 
      {type: widgetsEnum.rings4, id: 3},
      {type: widgetsEnum.rings4, id: 4},
    ]
  )

  const db = SQLite.openDatabase('db1.db');
  const date = `${new Date().getDate()}_${new Date().getMonth() + 1}_${new Date().getFullYear()}`

  const [sqlData, setSqlData] = useState([]);

  const [macros, setMacros] = useState({
    protein: 0,
    calories: 0,
    fats: 0,
    sugar: 0,
  })

  useEffect(() => {
    db.transaction(tx => {
      tx.executeSql(`SELECT * FROM Meals${date}`, null, 
        (txObj, { rows: { _array } }) => {
          setSqlData(_array);
        }) 
    })
  }, [db]);

  useEffect(() => {
    let newMacros = {
      protein: 0,
      calories: 0,
      fats: 0,
      sugar: 0
    }
    sqlData.forEach((element) => {
      newMacros.protein += element.protein;
      newMacros.calories += element.calories;
      newMacros.fats += element.fats;
      newMacros.sugar += element.sugar;
    })
    setMacros(newMacros);
  }, [sqlData])

  return (
    <SafeAreaView style={{
      flex: 1, 
      backgroundColor: COLORS.background,
    }}>
      <Header />
      <DraggableFlatList
        style={{ paddingHorizontal: 16, paddingVertical: 12, marginBottom: 134 }}
        data={widgets}
        onDragEnd={({ data }) => setWidgets(data)}
        renderItem={renderItem}
        ItemSeparatorComponent={() => <View style={{ height: 14 }}/>}
        keyExtractor={(widget) => widget.id}
        showsVerticalScrollIndicator={false}
      />
      <AddMeal />
      <TabBar />
    </SafeAreaView>
  )
}

export default App;

I tried to calculate the macros inside the useEffect where the data gets retrieved from the database, but this resulted in an infinite rerender loop.

2

Answers


  1. Chosen as BEST ANSWER

    Solution is to not open my database inside the component :facepalm:


  2. The call of setSqlData will trigger an rerender which wil recreate db vaiable and so on.

    Maybe you can use const db = useMemo(() => SQLite.openDatabase('db1.db'));

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search