Should i search the data in child or parent component in react?

I am creating a blog app with react. I have a search results page which shows users or posts. I have a parent component named search component. UserSearch and PostSearch are the child components. I am checking the url and query type in parent component. And show the child components based on the query by passing props. My question is should i fetch data in the child component or parent component? Currently the fetching is done in the child components. When the query doesn’t specify the type posts page is shown and posts are fetched from database. Then the user can switch to users section.
Here is my code.
The parent component:

export const Search = () => {
    const location = useLocation();
    const query = new URLSearchParams(location.search);
    const key = query.get('q');
    const type = query.get('type');   

    if (key==='' || key===null) {
        return (
            <SearchBar/>
        )
    }
    else if (type==='users'){
        return (
            <UserSearch prop={key}/>
           
        )
    }
    else {
        return (
            <PostSearch prop={key}/> 
        )
    }
}

The child posts component:

export const PostSearch = ({prop}) => {
    const navigate = useNavigate();
    const posts = useSelector((state)=> state.postReducer.posts);
    const dispatch = useDispatch();
    const [isLoading, setIsLoading] = useState(true);
    useEffect(() => {
        const get =  () => {
            dispatch(getPosts(prop));
          };
          get();
          setIsLoading(false); 
          console.log(posts);    
    },[]);
    const goToUser = ()=> {
        navigate(`/search?q=${prop}&type=users`);
    }

    if (isLoading) {
        return (
            <div >
              LOADING...
            </div>
        );
    }
    return (
        <Fragment>
            <button onClick={goToUser}>Users</button>
            {posts.length > 0 ? (
            <Fragment>        
            {posts.map((post) => (  
            <div key={post.id}>
                <h2>{post.title}</h2>
                {post.text}
            </div>
            ))} 
            </Fragment>
            ) : (
            <div>No results found</div>
            )}
        </Fragment>
    )  
}

Leave a Comment