Reputation: 4192
I have an application where user can search data depending by his input. In my application i try to use reselect.
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { searchPersonAction } from "./store";
const Search = () => {
const dispatch = useDispatch();
const selector = useSelector((s) => s);
const search = (e) => {
const txt = e.target.value;
dispatch(searchPersonAction(txt));
};
return (
<div>
<input onChange={search} placeholder="search" />
<ul>
{selector.name.map((p) => (
<li key={p.name}>{p.name}</li>
))}
</ul>
</div>
);
};
export default Search;
In my store
i have an array of persons like this:
export const persons = [
{
name:"jack",
age: 2
},
{
name:"Jim",
age: 14
},
{
name:"July",
age: 92
},
{
name:"Bill",
age: 1
},
{
name:"Carl",
age: 72
},
]
Now, when user search something, in the list appears the results according to the name which was searched by the user.
Question: Is the reselect usefull (protects from to many re-renders) in my case or not? Or using useSelector
, in the case above is enought?
Upvotes: 0
Views: 118
Reputation: 522
I don't think reslect here will be necessary. You can use useMemo
to achieve the same result.
import React, { useEffect, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { searchPersonAction } from "./store";
const Search = () => {
const dispatch = useDispatch();
const persons = useSelector((s) => s.persons);
const [query, updateQuery] = useState('');
const searchedPersons = useMemo(() => persons.filter(p => p.name.includes(query)), [query]);
const search = (e) => {
updateQuery(e.target.value);
};
return (
<div>
<input onChange={search} placeholder="search" />
<ul>
{searchedPersons.map((p) => (
<li key={p.name}>{p.name}</li>
))}
</ul>
</div>
);
};
export default Search;
Upvotes: 1
Reputation: 270
reselect
will be useful if you get array
or object
from store
for example:
store
state = {
persons: [
{
name:"Jack",
age: 2
},
{
name:"Jane",
age: 14
},
]
}
if you used selector
from react-redux
and if your typed 'J'
in the search field and used searchPersonAction
action, then it will change the array of persons
in the store
, but array stayed the same.
state = {
persons: [
{
name:"Jack",
age: 2
},
{
name:"Jane",
age: 14
},
]
}
then you receive rerender regardless of whether the data in the array has changed or not.
But if you use reselect
and when your typed 'Ja'
in the search field, it will be the same array, then you will not get a repeated render, because reselect
will memoize data
Upvotes: 0