1

say i created a variable in a functional component like so:

const [quizName, setQuizName] = useState("");

How could I change this value based on what a user enters into an input. My idea was this:

<input
    value={quizName}
    onChange={setQuizName(value)}
></input>

But it does not know what value is, how can i get the value into my quizName variable?

6Joeb
  • 11
  • 3

3 Answers3

1
<input
    value={quizName}
    onChange={(e)=>setQuizName(e.target.value)}>
</input>
roottraveller
  • 7,942
  • 7
  • 60
  • 65
bakar_dev
  • 936
  • 4
  • 13
1

the simplest way is to have a function in onChange of input like:

<input value={quizName} onChange={(e)=>setQuizName(e.target.value)} />

Its okay!, But Please for the sake of GOD please stop doing this!

Here is the reason:

you are creating a function on every change of input and running it! this is not ok of performance vise! especially if you do it in a large scale app every where in your components!

what you need to do is just use useCallback like below:

const [quizName, setQuizName] = useState("");

const handleInputChange = useCallback((e) => {
   setQuizName(e.target.value)
}, [setQuizName])


return (
   <input value={quizName} onChange={handleInputChange} />
)

here is a description of useCallback in react documentations:

https://reactjs.org/docs/hooks-reference.html#usecallback

amdev
  • 6,703
  • 6
  • 42
  • 64
0
onChange={setQuizName(value)}

When you call the function like this, it will get executed without waiting you to change it.

onChange={(e) => setQuizName(e.target.value)}

is the correct way to do it

Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35