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

120
Visualizações
React too many rending with useState

My Code :

import Item from './Item_att.js';
import axios from 'axios';

const Attraction_list = () => {
...
const [maindata, setMainData] = useState([]); //setData
const [postsPerPage] = useState(6);
...

let attList = async (areaCode, cityCode) => { //approach openAPI
    const url = `...`;
    try {
        const {data: res} = await axios.get(url)
        const list = res.response.body.items.item;

        console.log("rendering!")
        setMainData(list);
    } catch (err) {
        console.log(err);
    }
}

...

attList(1, 1).then(data => {console.log("then");}) //make maindata
const currentPosts = (tmp) => {    //slice data
    return tmp.slice(indexOfFirst, indexOfLast);
}

...

return (
    <div>
        ...
        <Item rlist={currentPosts(maindata)} moveTo={moveTo} area={area} city={"강남"}></Item>
    </div>
);
};

export default Attraction_list;

Function attList brings data from openAPI. Function currentPosts is executed when component Item is rendering, it returns a sliced list.

I think they executed only once,

Result : Too much rerendering on this program. Function attList and function currentPost executed too many times. I don't know why.

Why rerendering so much?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You should call the function attList inside a useEffect hook, else it will be called on each rerender of the component.

React.useEffect(()=>{

    attList(1, 1)

},[])
about 4 years ago · Juan Pablo Isaza Relatório

0

When you call

setMainData(list);

inside your attList function, react will rerender your component as there is a state change. This will then run your attList function again which is what is causing the loop.

To prevent this behaviour you can use the useEffect react hook to call the attList function once on the first render and only on the first render.

https://reactjs.org/docs/hooks-effect.html

about 4 years ago · Juan Pablo Isaza Relatório

0

You have made an infinity loop because the attList will execute setMainData which will then rerender the component again and therefor execute the attList again.

This is why you should use the useEffect hook, to make sure that the attList is only executed when you wan't it to. If you do as shown above, then it will only happen when the component is mounted.

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