DEV Community

Discussion on: Simple search form in REACT using hooks 🔎.

Collapse
 
clarity89 profile image
Alex K.

In this case setState will cause a re-render so the component will be rendered with the new value of filter, which is then applied to the filtered array before displaying the final results.

Thread Thread
 
maybebored profile image
Mayuran • Edited

I still think useEffect is a better approach (readable, maintainable), because calculating search in reality will be a side effect and could be left asynchronous, and not block rendering. When the search calculation is complete, by setting state we can trigger a re-render with the search results instead of blocking rendering, during the typing of a search term.

The functional component itself is the render function, I prefer to leave it as it is and use helper functions to perform side effects. But this is just my opinion, what do you think?

Thread Thread
 
clarity89 profile image
Alex K.

The two approaches are functionally similar. The main difference is that with useEffect approach you introduce extra unnecessary code, plus saving unnecessary values to the state, which can be derived at render time. This is similar to the discussion of storing derived data onto the state.

It's not that useEffect approach is wrong here, it's just that it can be simplified :)

Thread Thread
 
maybebored profile image
Mayuran

Got it, I'm learning a lot about React from this conversation. Thank you for the link :')

Thread Thread
 
clarity89 profile image
Alex K.

Sure thing! :) I also wrote an article about some of the common mistakes with React:

Thread Thread
 
bhushanstartup profile image
Bhushan Nayak

Hi Alex.. Can you make a component in react functional hooks which has sort, filter & search feature using your method?

The final result should be a single element which can be mapped to show the cards accordingly and It should not alter the existing data in the array but re-arrange/show accordingly.

I have a sample data as below:
const data = [
{
_id: "dress1",
image: "/images/fans.jpg",
title: "shirt",
description:
"This is for all the latest trends, no matter who you are, where you’re from and what
you’re up to. Exclusive to ASOS, our universal brand is here for you, and comes in all our fit ranges: ASOS Curve, Tall, Petite and Maternity. Created by us, styled by you.",
availableSizes: ["X", "L", "XL", "XXL"],
price: 29.9584
},
{
_id: "dress2",
image: "/images/mcb.jpg",
title: "Pants",
description:
"This is for all the latest trends, no matter who you are, where you’re from and what you’re up to. Exclusive to ASOS, our universal brand is here for you, and comes in all our fit ranges: ASOS Curve, Tall, Petite and Maternity. Created by us, styled by you.",
availableSizes: ["X", "M", "L"],
price: 18.78
}];

Thread Thread
 
amitdotcode profile image
amit-dotcode

i m facing problem this type data filterting