I am using react with TypeScript. I am mapping through a JSON file in react. It takes a second to render all the data in the browser. I'm using functional components. Here is the code. Please help me optimize the render time in the browser.
import users from "../data/users.json";
const Users:React.FC=() => {
const displayUsers=users.map((item){
return(
<p> {item.username} </p>
<p> {item.location} </p>
<img src={item.avatar}/>
)
})
return(
<div className='container'>
<div className='user'>
{displayUsers}
</div>
</div>
)
}
Issue: With your current implementation, users.map
will be executed at each render of the component.
You can optimize it using useMemo
hook:
import users from "../data/users.json";
const Users:React.FC = () => {
const mappedUsers = useMemo(() => {
return users.map((item) => {
return( <>
<p> {item.username} </p>
<p> {item.location} </p>
<img src={item.avatar}/>
</> )
})
}, [])
return(
<div className='container'>
<div className='user'>
{mappedUsers}
</div>
</div>
)
}
Now the map
function will be called only once when component mounts.
If you want to re-calculate the data using map
based on some dependency change, you can put it in dependency array []
of useMemo
.
If users
data is comping through props
of some parent component, you can use React.memo
to avoid re-rendering of (this) child component when props
are same. Here is a related post with demo for React.memo
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.