Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
Is there a way of running an if statement on whether or not props have changed in React

I currently have a component that holds a posts array, this component takes in a prop called sortBy which tells the component to either fetch data sorted by popular or new. The way my component is set up is upon initialization the posts are fetched then stored in redux, I only get new posts if my posts is empty. That way I'm not constantly fetching new data.

const posts = useSelector((state) => state.posts.posts);
useEffect(() => {
    const { sortby } = props;
                            // here I would like to check if props has changed
    if (Object.keys(posts).length === 0) {
      dispatch(getPostsAsync(sortby)).then((response) => {
        setLoading(false);
      });
    }
  }, [dispatch, props, posts]);

Now I would like to check if the sortBy props has changed value. So originally it might be sortby='-numLikes' but when I sortby 'new' it should then be sortby='-createdAt' after it changes I would like to tell Redux to fetch new data.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

All you need to do to get the behavior you want is to change the useEffect to:

const posts = useSelector((state) => state.posts.posts);
const { sortby } = props;
useEffect(() => {
  dispatch(getPostsAsync(sortby)).then((response) => {
    setLoading(false);
  });
}, [dispatch, sortby]);

Then the useEffect will run every time sortby is changed.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!