관리 메뉴

Silver Library (Archived)

So, how to useEffect? 본문

F5. Library of Tools/React.js

So, how to useEffect?

Ayin Kim 2023. 1. 11. 22:09
반응형

What is this?

useEffect is a hook in React that allows us to synchronise a component with an external system.

This can be used to handle a variety of tasks, like:

1. setting up a subscription

2. manually changing the DOM

3. fetching data

 

First of all, this is the typical and basic useEffect.

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // your code here
  }, [dependencies]);

  // rest of your component's code here
}

The first argument to useEffect is a function that contains the code we want to run.

This function is called an effect function. Inside this function, we can do things liek set up a subscription, fetch data, or change the DOM.

 

The second argument to useEffect is an array of dependencies. These are values from the component's state or props that we want to watch.

 

When any of these dependencieis change, React will re-run the effect function.

 

There was an example of using useEffect to subscribe to an external data source:

import { useEffect, useState } from 'react';

function MyComponent({ id }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    const subscription = someDataSource.subscribe(id, data => {
      setData(data);
    });
    return () => {
      subscription.unsubscribe();
    };
  }, [id]);

  if (data === null) {
    return <p>Loading...</p>;
  }
  return <p>Data: {data}</p>;
}

The component is subscribing to some external data source and passing an id prop to it.

 

Once the component is rendered, useEffect is called with an effect function that sets up the subscription and provides a cleanup function, which is called when the component is unmounted.

 

The component state is updated with the returned data and the component re-render the updated data.