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?

3

3 Answers 3

1
<input
    value={quizName}
    onChange={(e)=>setQuizName(e.target.value)}>
</input>
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

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.