I want to pass my component state to a custom hook and return true if my state changes as compared to initial state.
import { useRef, useEffect } from 'react'
export const useDirtyState = (props:any) => {
//Possibly use local state and set it to true and return that
const isFirstRender = useRef<boolean>(true)
const isDirty = useRef<boolean>(false)
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false
return
}
isDirty.current = true
console.log(isDirty.current) // is true
}, [props])
console.log(isDirty.current) // I return this and it is false :(
}
//In some other component
const isDirty = useDirtyStaate(state)//Expect this to be true when state is changed
The problem is that the outer console.log shows false even if props change because my effect runs after that (I guess?). How do I return the correct value from this hook ?
Edit: I tried adding a local state to the hook and setting it to true and returning it. While this approach works, I was wondering if there is a cleaner way as it seems to cause 1 extra render.