I'm coding a simple Reddit client in JavaScript using React, and I have an element in my header that changes the subreddit to be displayed - with the Lodash debounce applied inside of the React useMemo hook to prevent excessive handleChange calls while typing.
However, when the value prop of the input element is set to the appropriate useState variable, the input becomes impossible to alter.
This is the code that works, albeit with limitations I'm hoping to overcome:
import React, { useMemo } from 'react';
import debounce from 'lodash.debounce';
export const Header = ({ subreddit, setSubreddit }) => {
const handleChange = ({ target }) => {
setSubreddit(target.value)
}
const debouncedHandleChange = useMemo(() => {
return debounce(handleChange, 500)
}, [])
return (
Superliminal/ <input type='text' onChange={debouncedHandleChange} placeholder={subreddit} autofocus/>
)
}
Things get problematic when you define the value prop of the input element like so:
value={subreddit}
Currently, I don't understand why this causes the input to become inalterable, and I would prefer it to be the case that the value, and not just the placeholder, remains equal to the subreddit state variable. I especially don't understand because without the debounce implementation, you can define value as the state variable without issues.
If it's necessary, the code in the App.js file for setting the subreddit is simply:
import React, { useState } from 'react'
import { Header } from './components/Header/'
function App() {
const [ subreddit, setSubreddit ] = useState('all')
return (
<>
<Header subreddit={subreddit} setSubreddit={setSubreddit} />
</>
)
}
Could someone please explain to me why my code isn't working as intended and help me fix it?
Thanks in advance!!