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

194
Visualizações
How to set state from an Axios get request without causing a re-render

I am fairly new to React. I am currently having the problem that I am using the Axios Get request response to update one of my state variables.

However, I am currently facing the problem in which because the state variable is being updated, App gets re-rendered, which then calls the Axios Get request again (causing a sorta infinite loop).

How do I make it so that a Get request can change a variable, but doesn't re-render the component and call a Get request again?

function App(props) {
    let [sentenceData, setSentenceData] = React.useState({})

    const renderEnglishSentence = useCallback(function () {
        return <EnglishSentence sentenceData={sentenceData}/>;
    }, [sentenceData]);


    const fetchSentence = useCallback(function() {
        return axios.get('http://localhost:3030/getrandomunusedsentence')
    })

    fetchSentence().then((response) => 
        setSentenceData(response.data[0])
        return (
            <div>
                {renderEnglishSentence()}
            </div>
        )
    )
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You will want to use the useEffect hook for this. This will only render first time component is loaded.

import React, { useState, useEffect } from 'react';

function App(props) {
    useEffect(() => {
        const fetchSentence = useCallback(function() {
            return axios.get('http://localhost:3030/getrandomunusedsentence')
        })        
    }, []);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

  const [sentenceData, setSentenceData] = React.useState({})

  React.useEffect(() => {
    axios.get('http://localhost:3030/getrandomunusedsentence')
      .then(() => {
        setSentenceData(response.data[0])
    })
  }, [])

You can make the http request in the useEffect hook with zero dependencies ([])

about 4 years ago · Juan Pablo Isaza Relatório

0

Api calls should be handled as side effect. You should use useEffect hook for it with no deps, so it will be called once component is mounted.

useEffect(() => {
  const fetch = async () => {
    const response = await axios.get('http://localhost:3030/getrandomunusedsentence');
    const data = await response.json();
    setSentenceData(data);
  }
  
  fetch();
}, []);
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