HomeToolsAbout

useEffect

What is it

Performs side effects on your components.

  • Side effect is code that changes things outside the component.
  • Things like setting cookies or changing some markup (HTML) imperatively.

Also used to manage lifecycle of the function call.

  • When you define a function in the component, the function is executed during the rendering of the component (not before or after the render).
  • useEffect is used to run some sort of logic after the render, not during.
  • That, or it is used to call some logic specifically after a dependency is updated.

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:

  • The 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
AboutContact