I try to create custom hook to validate my inputs. But if custom hook returns an object, it re-creates on every change on the page
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue)
const [state, setState] = useState('')
return {value, state}
}
const user = useInput('')
That way I can get values using
user.value
user.state
But if there is multiple inputs on the page, one input triggers all other inputs re-create
useEffect(() => {
console.log('This triggers on every change on the page')
}, [user])
But if I destruct it first like this, than everything is fine
const {userValue, userState} = useInput('')
useEffect(() => {
console.log('Does not trigger on other inputs')
}, [userValue, userState])
Or if i return the object using useMemo, it works fine too:
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue)
const [state, setState] = useState('')
const obj = useMemo(() => {
return {value, state}
}, [value, state])
return obj
}
const user = useInput('')
What's the reason of this, why 'user' object changes even if there was no changes in it and it using useState on values. Why it stops re-creating after destructing or using useMemo?
I'm new to React and trying to understand it.