React - Custom Hook

BANG·2025년 9월 1일
import { useInput } from './Component/useInput';

const displayMessage = (message) => {
  alert(message);
};

const App = () => {
  // useInput 커스텀 훅 생성하여 사용
  const [
    inputValue, 
    handleChange, 
    handleSubmit
  ] = useInput('', displayMessage);

  return (
    <div>
      <h1>useIput</h1>
      <input value={inputValue} onChange={handleChange} />
      <button onClick={handleSubmit}>확인</button>
    </div>
  )
};

export default App;
import { useState } from "react";

export function useInput(initialValue, submitAction) {
  const [inputValue, setInputValue] = useState(initialValue);

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleSubmit = () => {
    setInputValue("");
    submitAction(inputValue);
  };

  return [inputValue, handleChange, handleSubmit];
};
import { useFetch } from './Component/useFetch';

const baseUrl = 'https://jsonplaceholder.typicode.com';

const App = () => {
  const {data, fetchUrl} = useFetch(baseUrl, 'users');

  return (
    <div>
      <h1>useFetch</h1>
      <button onClick={() => fetchUrl("users")}>Users</button>
      <button onClick={() => fetchUrl("posts")}>Posts</button>
      <button onClick={() => fetchUrl("todos")}>Todos</button>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
};

export default App;
import React from "react";
import { useFetch } from './Component/useFetch';

const baseUrl = 'https://jsonplaceholder.typicode.com';

const App = () => {
  const {data: userData} = useFetch(baseUrl, 'users');
  const {data: postData} = useFetch(baseUrl, 'posts');

  return (
    <div>
      <h1>user</h1>
      {userData && <pre>{JSON.stringify(userData[0], null, 2)}</pre>}
      <h1>post</h1>
      {postData && <pre>{JSON.stringify(postData[0], null, 2)}</pre>}
    </div>
  )
};

export default App;
import React, { useEffect, useState } from "react";

export const useFetch = (baseUrl, initialType) => {
  const [data, setData] = useState(null);

  const fetchUrl = (type) => {
    fetch(baseUrl + '/' + type)
    .then(response => response.json())
    .then(json => setData(json));
  };

  // 최초에만 더미 데이터를 가져오기 위함
  useEffect(() => {
    fetchUrl(initialType);
  }, []);

  return {
    data,
    fetchUrl
  }
};
profile
Record Everything!!

0개의 댓글