DEV Community

JOHNATAN STEVEN ORTIZ SALAZAR
JOHNATAN STEVEN ORTIZ SALAZAR

Posted on • Originally published at johnatanortiz.tech

useEffect React and TypeScript

React + Typescript

Using useEffect in a React component with TypeScript involves ensuring that your effect functions, dependencies, and cleanup functions are properly typed. Here’s how you can do this:

Basic Example

Here's a simple example of using useEffect with TypeScript:

tsxCopy code
import React, { useEffect, useState } from 'react';

const MyComponent: React.FC = () => {
  const [data, setData] = useState<string | null>(null);

  useEffect(() => {
    // Fetching data
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));

    // Cleanup (if necessary)
    return () => {
      console.log('Cleanup if necessary');
    };
  }, []); // Dependency array

  return <div>Data: {data}</div>;
};

export default MyComponent;

Enter fullscreen mode Exit fullscreen mode

Typing the State

When using state, you need to specify the type of the state variable. In the example above, useState<string | null> specifies that the state can be a string or null.

Example with Dependencies

If you have dependencies, you should also type them:

tsxCopy code
import React, { useEffect, useState } from 'react';

const MyComponent: React.FC = () => {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]); // Re-run the effect only if count changes

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default MyComponent;

Enter fullscreen mode Exit fullscreen mode

Cleanup Function

Here’s an example with a cleanup function, typically used for subscriptions or timers:

tsxCopy code
import React, { useEffect, useState } from 'react';

const TimerComponent: React.FC = () => {
  const [seconds, setSeconds] = useState<number>(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []); // Run once on mount and cleanup on unmount

  return <div>Seconds: {seconds}</div>;
};

export default TimerComponent;

Enter fullscreen mode Exit fullscreen mode

Fetching Data with TypeScript

For data fetching, you can define the type of the data you expect:

tsxCopy code
import React, { useEffect, useState } from 'react';

interface Data {
  id: number;
  name: string;
}

const FetchDataComponent: React.FC = () => {
  const [data, setData] = useState<Data | null>(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then((data: Data) => setData(data))
      .catch(error => console.error(error));

    return () => {
      // Any necessary cleanup
    };
  }, []); // Empty dependency array ensures this runs once on mount

  return <div>{data ? `Name: ${data.name}` : 'Loading...'}</div>;
};

export default FetchDataComponent;

Enter fullscreen mode Exit fullscreen mode

Handling Subscriptions

If you’re dealing with subscriptions, you can type the cleanup function appropriately:

tsxCopy code
import React, { useEffect, useState } from 'react';

const SubscriptionComponent: React.FC = () => {
  const [message, setMessage] = useState<string>('');

  useEffect(() => {
    const subscription = subscribeToMessages((newMessage: string) => {
      setMessage(newMessage);
    });

    return () => {
      subscription.unsubscribe();
    };
  }, []); // Empty array ensures the effect runs only once

  return <div>Message: {message}</div>;
};

function subscribeToMessages(callback: (message: string) => void) {
  // Dummy subscription function
  const interval = setInterval(() => {
    callback('New message received');
  }, 1000);

  return {
    unsubscribe: () => clearInterval(interval),
  };
}

export default SubscriptionComponent;

Enter fullscreen mode Exit fullscreen mode

Summary

  1. Type the state variables: Ensure that the state types are correctly defined.
  2. Type the data: When fetching data, define the type of the data you expect to receive.
  3. Type the cleanup function: Ensure that any cleanup functions are typed correctly.

By following these guidelines, you can effectively use useEffect in your TypeScript React components.

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay