Skip to content

Commit 6467cda

Browse files
author
Jeffrey-Xu
committed
fix: Improve state persistence by preventing reset on component mount
- Use useRef to track previous filters and detect actual changes - Prevent currentQuestionIndex reset on initial component mount - Only reset position when filters genuinely change, not on navigation - This should properly maintain question position when switching pages
1 parent cce25ef commit 6467cda

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/pages/PracticePage.tsx

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useEffect, useState, useCallback } from 'react';
1+
import React, { useEffect, useState, useCallback, useRef } from 'react';
22
import { ArrowLeft, BarChart3, Zap } from 'lucide-react';
33
import { Link, useLocation } from 'react-router-dom';
44
import QuestionCard from '../components/practice/QuestionCard';
@@ -55,6 +55,10 @@ const PracticePage: React.FC = () => {
5555
});
5656
const [isTransitioning, setIsTransitioning] = useState(false);
5757

58+
// Use ref to track previous filters for accurate change detection
59+
const prevFiltersRef = useRef(filters);
60+
const isFirstRender = useRef(true);
61+
5862
// Apply filters with progress data for bookmarks
5963
const filteredQuestions = React.useMemo(() => {
6064
return questions.filter(question => {
@@ -211,10 +215,21 @@ const PracticePage: React.FC = () => {
211215
}
212216
}, [displayQuestions.length, currentQuestionIndex]);
213217

218+
// Only reset when filters actually change (not on initial mount)
214219
useEffect(() => {
215-
// Reset to first question when filters change (but not when recommended questions change)
216-
setCurrentQuestionIndex(0);
217-
setShowExplanation(false);
220+
if (isFirstRender.current) {
221+
isFirstRender.current = false;
222+
prevFiltersRef.current = filters;
223+
return;
224+
}
225+
226+
// Check if filters have actually changed
227+
const filtersChanged = JSON.stringify(prevFiltersRef.current) !== JSON.stringify(filters);
228+
if (filtersChanged) {
229+
setCurrentQuestionIndex(0);
230+
setShowExplanation(false);
231+
prevFiltersRef.current = filters;
232+
}
218233
}, [filters]);
219234

220235
// Add keyboard shortcuts for navigation

0 commit comments

Comments
 (0)