본문 바로가기
728x90
반응형

프로젝트를 진행하면서 서버에 DummyData가 올라오기 전 useCallback 훅을 사용하여 버튼을 클릭했을 때 특정 파일이 기기에서 다운받아지도록 구현하였다. 

 

UseCallback이란?

useCallback은 React에서 함수를 캐싱하고 재사용하기 위해 사용되는 훅이다. 이를 사용하여 함수가 불필요하게 재생성되는 것을 방지하고, 메모리 및 성능을 최적화할 수 있다. 나는 useCallback 함수 안에 document.createElement('a') 를 사용하여 다운로드를 위한 elements를 생성하였고, 생성한 elements에 대한 URL을 임시로 생성되게 하여 다운되도록 하였다.

 

1. UseCallback 콜백 함수 지정

 const handleFileDownload = useCallback(() => {
   // 함수 추가 예정
  }, []);

2. 파일 이름과 내용 설정 및 다운로드를 위한 엘리먼트 생성

임시 파일의 형식, 이름과 내용을 적었다. 저는 txt 파일로 간단히 만들었습니다 :)

파일 다운을 위한 <a> 링크 태그와 함께 new Blob() 함수를 통해 파일을 생성하였습니다.

const handleFileDownload = useCallback(() => {
    // 파일 이름과 내용 설정
    const fileName = 'example.txt';
    const fileContent = 'This is the file content.';
    
    // 다운로드를 위한 element 생성
    const element = document.createElement('a');
    const file = new Blob([fileContent], { type: 'text/plain' });

  }, []);

3. 파일 정보 설정 및 클릭 시 다운로드 실행되도록 구현

element.href() 함수를 통해서 위에서 생성한 <a> 태그에 대한 url을 생성해준 뒤 element.download를 통해 element가 클릭되었을 때 다운로드가 되도록 설정한다. 

const FileDownloadButton = () => {
  // 파일 다운로드 콜백 함수 정의
  const handleFileDownload = useCallback(() => {
    // 파일 이름과 내용 설정
    const fileName = 'example.txt';
    const fileContent = 'This is the file content.';
    
    // 다운로드를 위한 element 생성
    const element = document.createElement('a');
    const file = new Blob([fileContent], { type: 'text/plain' });

    // 파일 정보 설정
    element.href = URL.createObjectURL(file);
    element.download = fileName;

    // 다운로드 실행
    element.click();
  }, []);

전체 코드 예시

import React, { useCallback } from 'react';

const FileDownloadButton = () => {
  // 파일 다운로드 콜백 함수 정의
  const handleFileDownload = useCallback(() => {
    // 파일 이름과 내용 설정
    const fileName = 'example.txt';
    const fileContent = 'This is the file content.';
    
    // 다운로드를 위한 엘리먼트 생성
    const element = document.createElement('a');
    const file = new Blob([fileContent], { type: 'text/plain' });

    // 파일 정보 설정
    element.href = URL.createObjectURL(file);
    element.download = fileName;

    // 다운로드 실행
    element.click();
  }, []);

  return (
    <button onClick={handleFileDownload}>다운로드 버튼</button>
  );
};

export default FileDownloadButton;
728x90
반응형