Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent react re-rendering images that are coming from an url?

This is how my app looks like right now:

enter image description here

The search and sort functions are working dynamically, as soon as I type a letter, it finds the match but re-renders all of them.

If I type "hunger", it finds the hunger games films, but it's getting images and rendering when it already has them. Is there any way to make this process just for once so I don't wait for every search, every sorting? I use Redux so data is coming from store, store is getting the data from local json file.

I thought about storing on local storage but I couldn't figure it out. As you can see there is no ComponentDidMount or Hooks.

This is the code of this page:

import React from "react";
import "./MoviesAndSeries.css";
import ListShowItem from "./ListShowItem";
import { getVisibleShows } from "../Redux/Selector";
import { connect } from "react-redux";
import FilterShowItems from "./FilterShowItems";
const Movies: React.FC = (props: any) => {
  return (
    <div className="movies">
      <FilterShowItems />
      {props.movies.map((movie: any) => {
        return <ListShowItem key={Math.random()} {...movie} />;
      })}
    </div>
  );
};

const mapStateToProps = (state: any) => {
  return {
    movies: getVisibleShows(state.movies, state.filters),
    filters: state.filters,
  };
};

export default connect(mapStateToProps)(Movies);
like image 591
İlker Avatar asked Sep 15 '25 15:09

İlker


1 Answers

You are using Math.random() as keys. The keys change all the time, and React can't know if the items already exist, so it re-renders all of them:

<ListShowItem key={Math.random()} {...movie} />;

Change the key to something stable, and unique, the movie id (if you have one) for example:

<ListShowItem key={movie.id} {...movie} />;
like image 90
Ori Drori Avatar answered Sep 18 '25 04:09

Ori Drori