Reputation: 611
I have the following element:
<p>{user.name}</p>
I can memoize it by doing:
useMemo(() => (
<p>{user.name}</p>
), [user]);
Now, let's say I have the following code:
users.map((user) => (
<p>{user.name}</p>
));
How can I memoize each element of the array so that only that element rerenders when a change happens (and not the whole array)?
Upvotes: 1
Views: 4269
Reputation: 550
I believe this is a possible use case for useCallback.
const renderUser = useCallback((user) => (
<p>{user.name}<p>
), []);
const users = users.map(renderUser);
You could be over-thinking things a bit, but it could also be this example that is making it hard to determine the why of this question, though.
The thing you're trying to memoize is, in its simplest form, a functional component with a single prop called name
. Why not just use it like that?
export const UserName = ({ name }) => (<p>{name}<p>)
And if there's no value from doing that, why not just render the result in line where it's needed like your non-memoized example?
users.map((user) => (
<p>{user.name}</p>
));
Unless there's some heavy calculation happening in the JSX template of your map function OR the fn component(s) used in that mapping, I don't think you stand to benefit much from memoizing something like this.
Upvotes: 2