Arun P S
Arun P S

Reputation: 21

FlatList renders each time view loads, even after using useCallback

I have an array of objects which is displayed in a FlatList. And I have TextInputs and a Button. On button click values from TextInputs are added to the existing FlatList. It works fine. But the FlatList is rendered many times even when typing in TextInput also. I used useCallback to control rendering. But doesn't work. Please help.

export default function FlatScreenDmo() {
  const [name, setName] = useState("");
  const [rollno, setRollNo] = useState("");
  const [student, setStudent] = useState([
    { rollno: "1", name: "Arun" },
    { rollno: "2", name: "Abin" },
    { rollno: "3", name: "Hari" },
    { rollno: "4", name: "James" },
  ]);

  const DisplayStudentFlatList = useCallback(
    ({ studentData }) => {
      console.log("DisplayStudent");
      return (
        <FlatList
          data={studentData}
          keyExtractor={(item) => item.rollno}
          renderItem={displayStudent}
        />
      );
    },
    [student]
  );

  const displayStudent = useCallback(
    ({ item }) => {
      console.log(item.rollno);
      return (
        <TouchableOpacity style={styles.studentRow}>
          <Text style={styles.studentText}>Name : {item.name}</Text>
          <Text style={styles.studentText}>Roll No : {item.rollno}</Text>
        </TouchableOpacity>
      );
    },
    [student]
  );

  function addStudent() {
    console.log("item.rollno");
    const newStudentList = student.concat({ name: name, rollno: rollno });
    setStudent(newStudentList);
  }

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.inputContainer}
        placeholder="Student Name"
        onChangeText={setName}
      />
      <TextInput
        style={styles.inputContainer}
        placeholder="Student Roll No"
        onChangeText={setRollNo}
      />
      <TouchableOpacity style={styles.button} onPress={addStudent}>
        <Text style={styles.studentText}>ADD STUDENT</Text>
      </TouchableOpacity>

      <DisplayStudentFlatList studentData={student} />
    </View>
  );
}

Upvotes: 1

Views: 654

Answers (1)

Arun P S
Arun P S

Reputation: 21

Solved.. Made FlatList as a custom component, removed useCallback() and used React.memo() on export.

Upvotes: 1

Related Questions