1

How to solve problem with too many re-renders in context ? I have the same context in other project and it works. I dont know what is wrong with it. Even if I comment out everything in provider when I use setState it is crash. Without using it works. I have wrapped App component with Provider. Even when Im wrapping single Component it crash.

CONTEXT


export const DataContext = createContext({
    list:null,
    dragCheck:null,
    setList:()=>{},
    setDragCheck:()=>{}
})

export const DataProvider = ({children}) => {
    let data = Data
    const [list,setList] = useState(null);
    const [dragCheck,setDragCheck] = useState(null);
    
    let path = window.location.pathname
    switch(path){
        case '/code':
            setList(data.code.list.questions)
            setDragCheck(data.code.drag_check)
            break;
        default:
            console.log("bad");
            break
    }
    return(
        <DataContext.Provider value={{
            list,
            dragCheck,
            setList,
            setDragCheck
        }}>
            {children}
        </DataContext.Provider>
    )
}
devil1321
  • 19
  • 6
  • you shouldn't use window.location.pathname for checking routes in react , use react router dom , and you shouldn't use switch statement like that in function component , you should write it inside useEffect hook – Goutham J.M Apr 20 '21 at 08:32
  • Okay. I understand but I was tried useEffect and its still crash. I cant even add one hook and change it value with setState. It is automatically show error with re-renders. Even if path is commented. – devil1321 Apr 20 '21 at 08:57
  • `setList` triggers a re-render, which triggers `setList`, which triggers a re-render, which triggers `setList`,.... If you want to initialise your state, do it directly in `= useState(myInitialvalue)`. If you need to change state depending on "external" var, use `useEffect` – dbuchet Apr 20 '21 at 09:44
  • Okey. It`s working. Thanks. I was copied switch to useEffect but it didn`t work. I copy all code from data to end of switch and it works. Thanks – devil1321 Apr 20 '21 at 10:52

0 Answers0