React useEffect only on Update

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

We can define a ref variable …


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Fatemeh Paghar

Have you ever thought what is the best way to run Redact’s useEffect Hook only on updates? Have you ever considered Redact’s 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 React’s 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 ref’s current property(didMount) after the first render of the component. When the didMount is false, it doesn’t 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 doesn’t 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.


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Fatemeh Paghar


Print Share Comment Cite Upload Translate Updates
APA

Fatemeh Paghar | Sciencx (2022-12-28T13:35:42+00:00) React useEffect only on Update. Retrieved from https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/

MLA
" » React useEffect only on Update." Fatemeh Paghar | Sciencx - Wednesday December 28, 2022, https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/
HARVARD
Fatemeh Paghar | Sciencx Wednesday December 28, 2022 » React useEffect only on Update., viewed ,<https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/>
VANCOUVER
Fatemeh Paghar | Sciencx - » React useEffect only on Update. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/
CHICAGO
" » React useEffect only on Update." Fatemeh Paghar | Sciencx - Accessed . https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/
IEEE
" » React useEffect only on Update." Fatemeh Paghar | Sciencx [Online]. Available: https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/. [Accessed: ]
rf:citation
» React useEffect only on Update | Fatemeh Paghar | Sciencx | https://www.scien.cx/2022/12/28/react-useeffect-only-on-update-3/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.