Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda