Search code examples
reactjsuse-effect

ReferenceError: Cannot access 'todos' before initialization App, react js


Getting the error 'ReferenceError: Cannot access 'todos' before initialization' on useEffect

function App() {
    //use effect
    useEffect(() =>{
        filterHandler();
    },[todos, status]); 


    //input text
    const [inputText,setInputText]=useState('');

    //todo list
    const[todos , setTodos] = useState([]);
    return (
        <div className="App">
            <header>
            <h1>Todo List</h1>
            </header>
            <Form 
                todos={todos} 
            />
        </div>
    )
}

Solution

  • You're using todos near the top of your component, but you don't create the variable until lower in the component. You will need to swap the order, so that you create it first, and use it after.

    function App() {
      //todo list
      const [todos, setTodos] = useState([]);
    
      //use effect
      useEffect(() => {
        filterHandler();
      }, [todos, status]);
    
      //input text
      const [inputText, setInputText] = useState("");
    
      return (
        <div className="App">
          <header>
            <h1>Todo List</h1>
          </header>
          <Form todos={todos} />
        </div>
      );
    }