Why infinite scroll pagination uses useState not using DOM append instead? - reactjs

I have seen many tutorials and articles which use useState to store all the records on a state instead of using ReactDOM or something to add HTML elements.
For example, they keep previous data and merge with new data and after that set in a useState hook
return [...new Set([...prevBooks, ...res.data.docs.map(b => b.title)])]
I have 2 questions
Isn't it a performance problem to have all the records in the state and to print it in JSX by map? There may be millions of records.
If I want to add a React component to the end of a div#ID, what should we do in the pagination?
For example, I have this block code:
<article className="col-sm">
<div className="row client-home-header-post-article-row" id="BlogsPosts">
{posts.entries.map((item) => (
<BlogItem post={item} key={item.id} size={4} />
))}
</div>
</article>
And with an action function like const showMore, add another <BlogItem post={item} key={item.id} size={4} /> to the bottom of BlogsPosts ID (like e.append)
I saw this post Append component in React, he suggested without recommending to use ReactDOM.createPortal, but I tested it like this, and it does not work
ReactDOM.createPortal(
<BlogItem post={item} key={item.id} size={4} />,
document.querySelector("#BlogsPosts")!
)
The posts I saw:
Append component in React
Reactjs append an element instead of replacing
How do you append a React Component to an html element
How to append React components to HTML element using .append()
How can I append a React component to an html element i?
Using document.querySelector in React? Should I use refs instead? How?
Append Element to an Existing Element React
Thank you in advance

Isn't it a performance problem to have all the records in the state
and to print it in JSX by map? There may be millions of records.
It depends. A performant server should try to keep the metadata it returns to the browser for each book small. That is, each book object should try to to contain minimal information like a title, author, price, and thumbnail URL, not all the data that the database knows about the book. Something like this:
{
"title":"MyBook",
"author":"Jeff Bezos",
"price":19.99,
"price_unit":"USD",
"thumbnail":"https://websitename.s4-bucket.region.UUID-1234"
}
Reducing the amount of data will boost performance by making searching through this data faster on the browser. Each object of this size is also less than 500 bytes, so if you are obtaining 50 items at a time you're only retrieving 25KB data per request, which with modern speeds only takes a few milliseconds.
If I want to add a React component to the end of a div#ID, what should
we do in the pagination?
You can use a useMemo hook which will update the BlogItem components you have rendered when the posts change. Something like this should work:
const blogItems = useMemo(()=>posts.entries.map((item) => (
<BlogItem post={item} key={item.id} size={4} />
)), [posts.length])
Then in your JSX just do this:
<article className="col-sm">
<div className="row client-home-header-post-article-row" id="BlogsPosts">
{blogItems}
</div>
</article>

Related

Can one React component render by 2 classes?

Can one React component render by 2 classes? Just like I did in the picture.
I tried the above. It gives me another error Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of "Groups".
The button component Im using in Groups method(Groups.jsx) like this way.
const Groups = (props) => (
<div className = 'panel'>
<h2>Groups</h2>
<button >Get Groups</button>
<div className = 'group-list'>
{props.groups.map((group) =>
<GroupsEntry name = {group.name}
members = {group.members}/>
)}
</div>
</div>
);
Do you guys have any idea about this? Thank you
I will try to clarify a little.
You can render a component from whatever parent component you want.
By in the case of your picture, what is telling you that the first component in tree, was App.js, and then App.js rendered Groups.js component, and Groups.js rendered your actual component.
In the same page, the warning you are seeing about using "key" is because you need to set a unique key value for each element that you are rendered as a list, a repeated item. This is because the internal react work to compare if it has to rerender again your component needs it. You will have performance problems (not in an easy example...) if you dont add it. Normally you use the id of the object you are rendering.
I hope i clarified a little.
Yes, a component can be rendered as many times as you would like. The issue is that you are mapping over an array and returning an element. React requires that you put a unique key prop on these elements that ideally are consistent between renders.
You can try to update your code to be something like the following:
const Groups = props => (
<div className="panel">
<h2>Groups</h2>
<button>Get Groups</button>
<div className="group-list">
{props.groups.map(group => (
<GroupsEntry key={group.name} name={group.name} members={group.members} />
))}
</div>
</div>
);
This is assuming group.name is unique. If you have a unique identifier (eg: group.id) that would be ideal.
For more examples and why this is necessary you can checkout the official docs: https://reactjs.org/docs/lists-and-keys.html

Loading dynamic links based on state

I'm having trouble rendering a dynamic ReactRouter menu.
I have a component, <MyApp />. In the componentDidMount() method of <MyApp />, i'm calling an API. the API returns an array of articles. I then set the state of <MyApp /> with these new articles.
.....
this.setState({
isLoaded: true,
articles: result
});
Now, I load a new component, <ArticlePage articles={this.state.articles} />
Slight tangent - This new <ArticlePage /> is made with a function component, not a class component. The reason being, is I had trouble using ReactRouter inside Class components.
function ArticlePage(props){}... now exists. Props holds my array of articles.
Inside ArticlePage(), i want to create a reactRouter link for each of the articles in the array that i'm passing in as props. This is where i'm having trouble.
In my head, I need to loop over each of the props.articles array elements, and create a reactRouter link element..
<ul>
{props.articles.map(item =>
(
<li>
<Link to={`${url}/${item.article_id}`}>{item.title}</Link>
</li>
))}
</ul>
The problem is, my links are not being displayed on the page. Debugging suggests that when the page renders and the .map loop above runs, the array is empty. Using Chrome developer tools, I can see that the props.article for that component does in deed contain all the articles. However, i am of course looking at this object in slower time than when the page renders, so it has had time to complete.
What is it, that I am doing wrong? Perhaps I should be loading and passing the articles state in a different way?

Can we add events on react fragment?

In my case, I have to wrap up the content in the parent component without adding extra div element to the DOM. So, I wrapped the element with the react fragment. I got a use case to add the native browser event to the react fragment, Is that even possible?
Short answer, no, you can't add events on React Fragments. There is a detailed discussion over here, but as such, I don't think React Fragments will be supporting event handlers in the near future.
You may convert the your React Fragment (from <> </>) to a div element instead, and attach events to them.
return <div onClick={() => handleClick()}> </div>;
You can't add events on react fragment.
you can only add key only to react fragments like
<React.Fragment key={id}>
.....
</React.Fragment>
not with this
<key={id}>
.....
</>

Improve the performance of Reactjs for rendering large amount of components

I am developing a gallery and I have a performance problem when I exceed 200 components.
Currently in my gallery I can filter images and sort them according to certain attributes.
I tried to use the "Lazy Load" to improve the performance but it brings me other problems that I did not have before. Moreover it does not solve the problem if I still display all my elements.
I would like to try a thing a bit like "react-virtualized" which updates the DOM permanently but I do not really know how to do it and I have the impression that "react-virtualized" was not thought for operate with entire components.
My Gallery component looks like that:
const Gallery = memo(props => {
const { imgs } = props;
const { onClickHere } = props;
return (
<div className="cards-container">
{imgs.map((img, index) => (
<GalleryImage
img={img}
index={index}
onClickHere={onClickHere}
/>
))}
</div>
);
});
My Image component looks like that:
const Image = props => {
const { img } = props;
const { index } = props;
const { onClickHere } = props;
const { alt } = props;
return (
<div className="cards-child">
<div className="gallery-card">
<img className="gallery-thumbnail" src={img.uri} alt={alt} />
<div className="card-info">
<span className="card-info_text">
<span className="badge badge-secondary">
{img.attr.join(", )}
</span>
</span>
</div>
<span className="card-icon-open fa fa-expand" onClick={e => {onClickHere(e, img, index);}} />
</div>
</div>
);
};
These components display a clickable image list that is all the same size.
Do you know if I can actually use react-virtualized and did it badly (if that's the case can you help me to see more clearly) or do you know a way to improve these performances ?
On one hand we have the render cycle from the Virtual DOM. In this case React will render every component when its props change or when its parent renders.
To improve performance here you could memoize the component so that it will only render if its props change, and not when the parent changes. So in your case, you probably want to memoize Image rather than Gallery. Note that Gallery is receiving onClickHere and passing it to Image. Make sure the callback is wrapped in a useCallback so a new reference is not created on every render (which memo would recognize as a new parameter and render the component).
On the other hand we have the actual DOM rendering. In this case React will only render anything if there is a change, and only change the necessary HTML.
Virtualization plugins help to avoid rendering all the HTML, and only redering the necessary. This is helpful so the browser has the minimum necessary HTML, because if the amount of nodes is large it might be laggy. Before implementing these try to reduce the amount of divs inside Image to a minimum.
Only apply performance improvements when necessary and test to see if you are getting benefits from them or not. In your case the main issue might be displaying too many HTML elements. Also it seems like your map function is missing a key.

Twinkling images in a component

I have component with navigation, on click item to child component passed in props some params, one of params - object 'itemImage' with className and url, like this:
{
url: '/static/image.svg',
className: 'absolute hidden md:block min-w-53 lg:min-w-68 mt-30 lg:mt-19 -ml-28 lg:-ml-75',
}
In child component ItemComponent:
{
itemImage &&
<img className={itemImage.className} src={itemImage.url} alt='' />
}
ItemComponent is selected from an array according to the order of the element in navigation (it is responsible for the object passed to the child component), since the list of navigation elements and elements of the array of pictures are not related and of different lengths. The sample is implemented on the basis of an index in map for objects and an index in an array with pictures, to be more precise.
Problem:
the pictures flicker as the state of the parent and the child is updated, is it possible to somehow avoid this and make the change of the picture clear without the flickering of the previous card.
You can use the below-mentioned code to render the Array of Images.
<>
{this.props.Images.map(item=>{
return (item)
})}
<p>
{JSON.stringify(this.state)}
</p>
<p>
{JSON.stringify(this.props.changed)}
</p>
<button onClick={this.props.onChange}>Change</button>
<button onClick={this.onCurrentChange}>Current State Change</button>
</>
Please check the demo here Demo
You can make somethings to try to prevent that.
1- Add a key prop to the elements. It help react understand that it is the same data from before and not re-render that piece.
2- Use react PureComponent on the flickering element https://reactjs.org/docs/react-api.html#reactpurecomponent to prevent the re-render
3 - Instead of purecomponent implement shouldComponentUpdate

Resources