1
I am studying React.js and to fix the contents I am developing an application (SPA), the case is that I found the code barely readable even after applying the context api to solve the prop Drilling. I am creating a game of questions and answers, I would like guidance/help in the best way to apply this solution (context api). I created all the 'States' in the context I named as global, but it was like pushing the dirt under the carpet.
import React, { createContext, useState } from "react"
import Questions from '../data/questions.json'
export const GlobalContext = createContext()
export default function ScreenProvider({ children }) {
const [screen, setScreen] = useState('start');
const [ questionIndex, setQuestionIndex ] = useState(0);
const [ condition, setCondition ] = useState('stop');
const [ miss, setMiss ] = useState(null);
const [ stop, setStop] = useState(null);
const [ firstQuestion, setFirstQuestion ] = useState(false);
const [ questionList, setQuestionList ] = useState(Questions);
const [ question, setQuestion ] = useState(questionList[0]);
const [ selected, setSelected ] = useState(0);
const [ timer, setTimer ] = useState(0);
const [ timerIsActive, setTimerIsActive ] = useState(false);
const [ showCorrect, setShowCorrect ] = useState(false);
const [ confirmAnswer, setConfirmAnswer ] = useState(false);
const [hideMenu, setHideMenu] = useState("hide-menu menu-area");
const [ playerName, setPlayerName ] = useState('');
const [ stopGame, setStopGame ] = useState(false);
const [ jumpQuestion, setJumpQuestion ] = useState(false);
const [ timesToJump, setTimesToJump ] = useState(3);
return (
<GlobalContext.Provider
value={{
screen,
setScreen,
questionIndex,
setQuestionIndex,
condition,
setCondition,
miss,
setMiss,
stop,
setStop,
firstQuestion,
setFirstQuestion,
questionList,
setQuestionList,
question,
setQuestion,
selected,
setSelected,
timer,
setTimer,
timerIsActive,
setTimerIsActive,
showCorrect,
setShowCorrect,
confirmAnswer,
setConfirmAnswer,
playerName,
setPlayerName,
stopGame,
setStopGame,
jumpQuestion,
setJumpQuestion,
timesToJump,
setTimesToJump,
hideMenu,
setHideMenu
}}
>
{children}
</GlobalContext.Provider>
)
}
I ask dirt so that the code does not get all these Tates accumulated and how to improve this code.
It’s hard to answer without seeing the whole code - which is probably giant. But it seems to me that you’re putting the responsibilities in the wrong place. A single component with all this
state
it’s kind of weird, the responsibility of some can probably be passed on to some child component.– Rafael Tavares
is as Rafael Taraves quoted, has a lot of variable and needs to be everything there, what is the purpose of these variables there? A hint could be an object in this case
– novic