The real use of useEffect in ReactJS

Yes you are right ! , we are here to find out the real use of useEffect hook in ReactJS

// parent componentimport React, { useState } from "react";import AnotherComponent from "./AnotherComponent";function UseEffectExample() {const [v1, setV1] = useState("");const [v2, setV2] = useState("");return (<React.Fragment><p>Prop 1<input type="text" value={v1} onChange={(evt) => {setV1(evt.target.value)}} /></p><p>Prop 2<input type="text" value={v2} onChange={(evt) => {setV2(evt.target.value)}} /></p><AnotherComponent prop1={v1} prop2={v2} /></React.Fragment>);
}
export default UseEffectExample;
// child componentimport React, { useEffect } from "react";function AnotherComponent(props) {const {prop1,prop2} = props;useEffect(() => {console.log('This will always trigger , on load and prop change ,{{ComponentDidMount}}');})useEffect(() => {console.log('This will trigger only once {{ComponentWillUnMount}}');}, [])useEffect(() => {console.log('This will trigger when prop1 changes {{componentDidUpdate}}');}, [prop1])useEffect(() => {console.log('This will trigger when prop2 changes  {{componentDidUpdate}}');}, [prop2])return(<p>Another one with props: {prop1}, {prop2}</p>)}export default AnotherComponent;
useEffect(() => {console.log('This will always trigger , on load and prop change ,{{ComponentDidMount}}');})
useEffect(() => {console.log('This will trigger only once {{ComponentWillUnMount}}');}, [])
useEffect(() => {console.log('This will trigger when prop2 changes {{componentDidUpdate}}');}, [prop2])

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store