The useEffect hook is just a function that takes two parameters
I have been using the React framework for the past year and a half, and I noticed that most people struggle with hooks.
I have never liked writing Vanilla JavaScript, and React is my first JavaScript framework. When I started learning React, the hooks were already out in the market. As a result, I did not struggle with how to use them.
However,
The syntax of useEffect was always looking weird to me.
Look at this:
useEffect(() => {}, []);
After a while, I understood that useEffect is not a magical React stuff but rather a function that takes two parameters: Function & Array
As you might know, if we exclude the array parameter from the useEffect hook, the function that we put into the first parameter will be executed every render:
const hey = () => console.log(‘hey’)// I do not know whether calling the function we want inside another function changes anything ¯\_(ツ)_/¯useEffect(hey)useEffect(() => hey())
If we include an empty array, the function will be called only once.
const hey = () => console.log(‘hey’)useEffect(hey, [])useEffect(() => hey(), [])
If we add an item to the array, whenever that item changes, the function will be called additional to the initial call
const [items,setItems] = useState([])const hey = () => console.log(‘hey’)useEffect(hey, [stuff])useEffect(() => hey(), [stuff])
I hope this simple post could show you not to be scared of the useEffect hook syntax.