Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to use React useEffect Hook

most common cases how useEffect implementation: 
- fetch data from API, 
- directly updating the DOM, 
- use timers and real-time data displays (such as BTC current price)
- validating input field
- trigger animation on new array value
- 

// 1- EVERY RERENDER
useEffect( () => {
  console.log("It runs everytime this component rerenders")
  });

// 2- ON MOUNT
useEffect( () => {
   console.log("It Only runs once (When the component gets mounted)")
   }, []);

// 3- DEPENDING ON CONDITION
useEffect( () => {
   console.log("It runs everytime the condition is changed")
   }, [condition]); //basically the dependency array determines when the rerender happens

// 4- DEPENDING ON CONDITION, BUT WITH "clean up"
useEffect( () => {
	console.log("It runs everytime my condition is changed")
	return () => {
    	console.log("Use this return as a 'clean up tool' (it runs before the actual code)")
        }
    }, [condition]);
Source by it.reactjs.org #
 
PREVIOUS NEXT
Tagged: #React #useEffect #Hook
ADD COMMENT
Topic
Name
7+8 =