Introduction to State Management in ReactJS

State Management with useState and useEffect in ReactJS

React’s state system helps us remember things like which category was chosen, which question we’re on, and how many points the user has scored.

We use useState() to store values that can change during the app's lifecycle. For example, in App.jsx, we store which step the app is in (welcome, quiz, or score):

const [step, setStep] = useState("welcome");

In Quiz.jsx, we manage state for:

  • The list of fetched questions
  • The current question index
  • The user's score
  • Whether data is loading

Example:

const [questions, setQuestions] = useState([]);
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [score, setScore] = useState(0);

We also use useEffect() to run code when the component loads. This is where we fetch questions from the trivia API:

useEffect(() => {
  fetchQuestions(category);
}, [category]);

This hook runs only once when the component mounts or when the category changes.