Home > front end >  How can I use useMemo React Hook in this example
How can I use useMemo React Hook in this example

Time:03-16

What am I doing wrong here? I want to utilise useMemo so that my RenderItems component doesn't keep flickering when the state (Data2) changes. The Data2 array is in place of an item in my apps state. In practice, Data2 is data fetched from an api, and thus is subject to change and update.

I'm not looking for an alternative in this case, I'd just like to know how to use useMemo in this example - thanks!

import React, { useMemo } from 'react';
import {
  View,
  Text
} from 'react-native';

const CoursesWidget = (props) => {

  const Data2 = [{ id: '11' }, { id: '22' }, { id: '33' }];

  const coursesArray = Data2;

  const RenderItems = useMemo(() => {
    return (
      coursesArray
        .map((course) => {
          return (
            <View key={course.id}>
              <Text>{course.id}</Text>
            </View>
          );
        }),
      [coursesArray]
    );
  });

  //const Finito = useMemo(() => RenderItems(), [])

  return (
    <View>
      <RenderItems />
    </View>
  );
};

export default CoursesWidget;

Snack: https://snack.expo.dev/rr8toaABT

CodePudding user response:

I would suggest that you use a state and a FlatList instead of creating the elements using map. There is no need to use useMemo at all in this scenario and it will not fix your issue.

import React, { useState } from 'react';
import {
  View,
  Text,
  FlatList,
  SafeAreaView
} from 'react-native';

const CoursesWidget = (props) => {

  const [data, setData] = useState([{ id: '11' }, { id: '22' }, { id: '33' }])

  return (
    <SafeAreaView style={{margin: 20}}>
      <FlatList
        data={data}
        renderItem={({ item }) => {
           return <View>
              <Text>{item.id}</Text>
            </View>
        }}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
};

export default CoursesWidget;

Here is an updated version of your snack.

CodePudding user response:

All that needs to be changed is moving the dependency array that you pass to useMemo to be the last parameter, and instead of calling it in the return like a jsx component, you put the value in brackets since it's not really a function anymore:

import React, { useMemo } from 'react';
import {
  View,
  Text
} from 'react-native';

const CoursesWidget = (props) => {

  const Data2 = [{ id: '11' }, { id: '22' }, { id: '33' }];

  const coursesArray = Data2;

  const RenderItems = useMemo(() => {
    return (
      coursesArray
        .map((course) => {
          return (
            <View key={course.id}>
              <Text>{course.id}</Text>
            </View>
          );
        })
    );
  }, [coursesArray]);

  //const Finito = useMemo(() => RenderItems(), [])

  return (
    <View>
      { RenderItems }
    </View>
  );
};

export default CoursesWidget;

Here's the snack: https://snack.expo.dev/5GbI-k8Pb

  • Related