DEV Community

Cover image for useEffect() - What You Need to Know for Acing Tech Interviews!
Alberto Cubeddu
Alberto Cubeddu

Posted on

useEffect() - What You Need to Know for Acing Tech Interviews!

Introduction

useEffect() is one of the React Hooks which, by definition, allow functional components to access state and lifecycle features. They are used to handle side effects, operations that should be separated from the main rendering process. Example of side effects include data fetching, manipulation of the DOM and subscriptions.

The common rules

  1. Hooks must be used in React function components.
  2. Only call them at the top level of a component and avoid conditional use!
  3. Follow the naming convention ("useHook").

Examples

Use in class components (incorrect)

import React, { useState } from 'react';

class SSComponent extends React.Component {
  constructor(props) {
    super(props);
    const [number, setNumber] = useState(0);  // Incorrect: Hooks cannot be used here!!
  }

  render() {
    return <div>{`The count is ${count}`}</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Top Level Use (correct):

function SSComponent() {
  const [name, setName] = useState('');  // Correct: at the top level
  useEffect(() => {
    document.title = name;  // Correct: at the top level
  });

  return <input value={name} onChange={e => setName(e.target.value)} />;
}
Enter fullscreen mode Exit fullscreen mode

Used inside conditional (incorrect)

function SSComponent({ isLogged }) {
  if (isLogged) {
    useEffect(() => {   // Incorrect: inside a conditional block
      console.log('The above will cause issues');
    });
  }
  return <div>Skill Society</div>;
}

Enter fullscreen mode Exit fullscreen mode

How it works - Show me some examples

Let's start with the basic syntax:

useEffect(effect, dependency);
Enter fullscreen mode Exit fullscreen mode

Effect: F(x) containing the logic.
Dependency: When presents illustrate in an array format which dependencies are watched. If any of the dependencies changes, the useEffect will trigger the F(x).

Default Behaviour (execute every time)

It execute every time your component is rendered

useEffect(() => {
  console.log('Runs on every render!');
});
Enter fullscreen mode Exit fullscreen mode

Execute once (at component mount)

This emulate the componentDidMount executing the function as soon as the component is initially rendered.

useEffect(() => {
  console.log('Runs only on the first render!');
}, []);

### Execute when a dependency is updated
`const [website, setWebsite] = useState('https://skillsociety.com.au');

useEffect(() => {
  console.log(website); //Run on first render + anytime the dependency value changes!
}, [website]); 
Enter fullscreen mode Exit fullscreen mode

Execute only when a dependency is updated


import { useEffect, useRef, useState } from "react";

export default function App() {
  return (
    <div>
      <h1>Hello Dev.to Reader!</h1>
      <h2>Visit our website Skill Society</h2>
      <a href="https://skillsociety.com.au>SkillSociety</a>
      <MyComponent value={2} />
    </div>
  );
}

function MyComponent({ value }) {
  const isInitialMount = useRef(true);

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false; // Set to false after the first render
      console.log("initial mount, put logic here if you want to execute when the component is rendered");
    } else {
      // This code runs only when `value` changes, not on initial mount
      console.log("Value updated to:", value);
    }
    // This setup ensures the effect is ignored on the initial mount,
    // but runs on subsequent updates to the dependency `[value]`.
  }, [value]); // Dependency array includes only `value`

  return <div>Value is: {value}</div>;
}

Enter fullscreen mode Exit fullscreen mode

With CleanUp functionality

const [count, setCount] = useState(0);

useEffect(() => {
  const intervalId = setInterval(() => {
    setCount(prevCount => prevCount + 1);
  }, 1000);

  return () => clearInterval(intervalId); // Cleanup function to clear the interval
}, []); // Empty dependency array to set up the interval once
Enter fullscreen mode Exit fullscreen mode

The above are just the basic concepts!

Yes, we're only covering the essential concepts you must know for a tech interview. If you want to learn more about advanced dependency management, detailed lifecycle control, optimisation techniques, error handling, and concurrency issues, please DM me on LinkedIn!

Follow me on LinkedIn

Top comments (0)