React Hooks: useEffect
In a previous post, I spoke about how I used useEffect
to keep track of changes, and update components with said change. Here, I’ll dive a little deeper into what is going on behind my code.
So what is useEffect
? useEffect
is similar to componentDidMount
and componentDidUpdate
in the sense that it runs after the first render and after each update. With each run, useEffect
executes the function passed into it. Let’s take a look at this example:
const [logoColor, setLogoColor] = useState("#FEFEFE")const location = useLocation()useEffect(() => { switch (location.pathname) { case "/about": setLogoColor("#636363") return logoColor default: setLogoColor("#FEFEFE") return logoColor }}, [location])
useEffect
takes in two arguments: the function to be executed upon change, and the variable to be observed for changes as an array. I use another Hook, useLocation
to check for changes in my window location. Whenever that gets updated, the switch statement runs, changing my logo color according to the path.
The second argument, [location]
, tells React not to execute the function if the location variable has not changed, which helps to improve performance!