Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 28, 2022 01:35 pm GMT

React useEffect only on Update

Have you ever thought what is the best way to run Redacts useEffect Hook only on updates? Have you ever considered Redacts useRef Hook as a solution to create an instance variable and track the lifecycle of a component?

We can define a ref variable in the functional component in React when It is necessary to keep tracking some state without using Reacts re-render mechanism. illustration, we can determine if a component was rendered for the first time or if it was re-rendered. First, consider the following example:

const UseEffectUpdates = () => {    const[ txtValue, setTxtValue] = useState({        value1:"",        value2:""    })    const [txtColor, setTxtColor] = useState("white");    const [toggle, setToggle] = useState(true);    const didMount = useRef(false);    const handleToggle = () => {        setToggle(!toggle);    };    const txtChange1 = (event)=>{        event.preventDefault();        console.log("textbox change 1");        setTxtValue({...txtValue, value1:event.target.value});        if (txtValue.value2 ===  event.target.value){            setTxtColor("green");        }    }    const txtChange2 = (event)=>{        event.preventDefault();        console.log("textbox change 2");        setTxtValue({...txtValue, value2:event.target.value})        if(txtValue.value1 === event.target.value){            setTxtColor("green")        }    }    useEffect(() => {        if (didMount.current) {        console.log('I run only if toggle changes.');        } else {        didMount.current = true;        }    }, [toggle]);    return (        <div>            <input style={{backgroundColor:txtColor}} type="text"  placeholder="name1" onChange={txtChange1}  value={txtValue.value1}/>            <br/>            <input style={{backgroundColor:txtColor}} type="text"  placeholder="name2" onChange={txtChange2}  value={txtValue.value2}/>            <br/>            <button type="button" onClick={handleToggle}>                Toggle            </button>                </div>    );};

In the above sample code, the didMount variable is initialized with true, because it is supposed to be the component rendered the first time when it gets initialized. Also using the useEffect hook with toggle dependency to update the refs current property(didMount) after the first render of the component. When the didMount is false, it doesnt trigger a re-render thought.When you run the above code, the useEffect just runs when clicking on the toggle button, and the handleToggle event runs. On the other hand, when the textboxes are changed the useEffect doesnt run.

That is all. If you want to keep track of the state in your React component which shouldn't cause it to re-render, React's useRef Hooks is an option to create an instance variable for it.


Original Link: https://dev.to/fpaghar/react-useeffect-only-on-update-4oj7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To