skip to Main Content

When the input is onChange, I want the value of the variable to change and be written to the console. But when changed it writes undefined to the console. Can you help me please ?

import './App.css';
import React,{useState,useEffect} from 'react';

function App() {
    let [message,setMessage] = useState("");
    
    useEffect((message) => {
    console.log(message);

    },[message])
return(
<div> 
    <input type="text" onChange={e => setMessage(e.target.value)}  />
</div>

)}
export default App;

Why does it say undefined every time there is an onchange?

2

Answers


  1. The issue is, that you wrote

    useEffect((message) => {
        console.log(message);
    },[message])
    

    but it should be like this

    useEffect(() => {
        console.log(message);
    },[message])
    
    Login or Signup to reply.
  2. It is because you declare message to useEffect as an argument in the callback function and that is a different message than the state, it is local to the useEffect.

    You need to write

      useEffect(() => {
        console.log(message);
    
        },[message])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search