Why isn’t my useEffect running on render?

In my code (React Native) to avoid the “Too many re-renders” error I used a useEffect hook. I would expect the useEffect to run when the component PracticeTest first runs but it doesn’t. Can someone explain how I can fix it?

function PracticeTest({setCurrentMode}){
  const [index, setIndex] = useState(0);

  const [selected, setSelected] = useState(0);
  const [feedback, setFeedback] = useState('');
  const [score, setScore] = useState(0);
  
  // Create 'isCorrect' var to designate if ready to move on to the next question
  const [isCorrect, setIsCorrect] = useState(false);

  // get only the questions needed
  testQuestions = require('./testQuestions.json');
  let questionAnswers = [];

  let firstQuestionIndex;
  let lastQuestionIndex;
  let testLength = lastQuestionIndex - firstQuestionIndex;
  const [shuffled, setShuffled] = useState(false);

  const [done, setDone] = useState(false);



  
  
  useEffect(() => {
    questionAnswers = [];


    for(var i=0; i<testQuestions.length; i++){
      if((i>=firstQuestionIndex) && (i< lastQuestionIndex)){
        questionAnswers.push(testQuestions[i]);
        
      }
    }
      
      
      
    shuffle(questionAnswers);
      
    testLength = 10;
    shuffled = true;
    
  });
    

  // if quizType is "practiceTest" then the questions will be randomly selected and jumbled
  // Source for shuffle function (modified by me): /questions/2450954/how-to-randomize-shuffle-a-javascript-array
  function shuffle(array) {
    if(shuffled){
      console.log("ALREADY SHUFFLEDDDDDDDDDDDDDD");
    }
    else{
      
      let currentIndex = array.length;
    
      // While there remain elements to shuffle...
      while (currentIndex != 0) {
    
        // Pick a remaining element...
        let randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
   
        // And swap it with the current element.
        [array[currentIndex], array[randomIndex]] = [
          array[randomIndex], array[currentIndex]];
      }
      console.log("Shuffle!!");
    }
  }
  
  

  let question = questionAnswers[index].question;


  function check(){
    if(selected == questionAnswers[index].correctID){
      // add 1 point to score if the feedback is blank
      if(feedback==''){
        setScore(score+1);
      }
      setFeedback('Correct!');
      setIsCorrect(true);
    }
    else{
      setFeedback("Try again");
    }
  }

  function proceed() {
    if((index + 1) >= testLength){
      // Code to be executed if done
      setDone(true);
    }
    else{
      setIndex(index + 1);
      setIsCorrect(false);
      setColor1('#FF6868');
      setColor2('#FF6868');
      setColor3('#FF6868');
      setColor4('#FF6868');
      setFeedback('');
    }
    
    
    
  }

  const [color1, setColor1] = useState('#FF6868');
  const [color2, setColor2] = useState('#FF6868');
  const [color3, setColor3] = useState('#FF6868');
  const [color4, setColor4] = useState('#FF6868');

  return (
    <View>
      {done ? 
        <QuizDone setCurrentMode={setCurrentMode} score={score} testLength={testLength}/>
      : 
        <View style={styles.app}>
          <Text style={styles.logo}>Testing your Knowledge</Text>
          <Text style={styles.question}>{question}</Text>
          <AnswerChoices setSelected={setSelected} index={index} questionAnswers={questionAnswers} color1={color1} color2={color2} color3={color3} color4={color4} setColor1={setColor1} setColor2={setColor2} setColor3={setColor3} setColor4={setColor4} />
          <BackButton setCurrentMode={setCurrentMode}></BackButton>
          {/** Feedback */}
          <View style={{
            position: 'absolute',
            width: 144,
            height: 42,
            top: 595,
            left: 63,
            justifyContent: 'center',
          }}>
            <Text>{feedback}</Text>
          </View>
          {/** Check Answer */}
          {
            isCorrect ? 
          <TouchableOpacity style={styles.checkButton} onPress={proceed}>
            <Text style={{color: 'white', alignSelf: 'center',}}>Move on</Text>
          </TouchableOpacity>
          :
          <TouchableOpacity style={styles.checkButton} onPress={check}>
            <Text style={{color: 'white', alignSelf: 'center',}}>Check</Text>
          </TouchableOpacity>
          }
        </View>
        }
    </View>
  )
}

I tried may things, like adding a console.log to see if the useEffect was even running, which it didn’t. And because the code inside of the useEffect isn’t running, the array “questionAnswers” has no value.

New contributor

user25911215 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

If You don’t use a dependency array, the useEffect will run on every render and is useless. If you only wan the effect to run on initial render, you can give an empty array as a dependency array: useEffect(() => {…}, [])

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật