Performs side effects
on your components.
Side effect
is code that changes things outside the component
.Also used to manage lifecycle of the function call.
useEffect
is used to run some sort of logic after the render
, not during.You can control when
these functions will be called and can get a guarantee that some functions will run after the rendering is complete (meaning, the DOM will be accessible).
useEffect(() => { //Runs on every render }); useEffect(() => { //Runs only on the first render }, []); useEffect(() => { //Runs on the first render //And any time any dependency value changes }, [prop, state]);
If the variable referenced in the dependency array is not primitive, you will likely run into infinite render loop:
useEffect
internally compares the dependencies by reference
.const [count, setCount] = useState(0); useEffect(() => { setCalculation(() => count * 2); }, [count]); // count is a primitive number variable const [someObj, setSomeObj] = useState({}); useEffect(() => { // new object passed every time with new address setSomeObj({field1: "this", field2: "that"}); }, [someObj])
Solution to infinite rendering problem:
const [someObj, setSomeObj] = useState({}); const { field1, field2 } = someObj; useEffect(() => { setSomeObj({field1: "this", field2: "that"}); }, [field1, field2]); // manually passing each field which is primitive