I have created a controlled component that constrains an input field to only 4 numbers. These numbers can be changed at any time and any time the number is four digits I want the result to be passed to a sibling component to action.
I am sending the value to the parent state and this re-renders and the sibling gets the value. But my component also re-renders and the input fields loses the value.
Should I just send the value to the parent let the parent re-render on every input change?
Or use Context?
Any insight would be great as I am new to React.
const NumberComp = ({setPostcode})=>{
const [ fieldValue, setFieldValue ] = useState('')
useEffect(()=>{
if(fieldValue.length == 4){
setPostcode(fieldValue)
}
}, [fieldValue])
const updateNumber = (e)=>{
const value = e.target.value
if(value.length > 4 || isNaN(value)) return
setFieldValue(value)
}
return <input onChange={updateNumber} value={fieldValue} type="text" />
}