Quiero pasar el estado de mi componente a un enlace personalizado y devolver verdadero si mi estado cambia en comparación con el estado inicial.
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
El problema es que el archivo console.log externo muestra falso incluso si los accesorios cambian porque mi efecto se ejecuta después de eso (¿supongo?). ¿Cómo devuelvo el valor correcto de este gancho?
Editar : Intenté agregar un estado local al enlace y configurarlo en verdadero y devolverlo. Si bien este enfoque funciona, me preguntaba si hay una forma más limpia, ya que parece causar 1 procesamiento adicional.
Simplemente almacene el valor original en una referencia y compárelo con el valor proporcionado durante el procesamiento:
const {useRef, useState} = React; // You can implement the value comparison using your preferred method function areValuesEqual (value1, value2) { return Object.is(value1, value2); } /** * TS: * function useValueChanged <T>(value: T): boolean */ function useValueChanged (value) { const originalRef = useRef(value); return !areValuesEqual(originalRef.current, value); } function Example () { const renderCountRef = useRef(0); renderCountRef.current += 1; const [count, setCount] = useState(0); const increment = () => setCount(n => n + 1); const didChange = useValueChanged(count); return ( <div> <div>Render count: {renderCountRef.current}</div> <div>Changed: {didChange ? 'Yes' : 'No'}</div> <button onClick={increment}>Clicks: {count}</button> </div> ); } ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script> <div id="root"></div>