Post

0814 React 수업

React (Chapter 9-10)

Chapter 9: Custom Hook

이 Chapter에서는 React에서 Custom Hook을 만드는 방법을 다룬다. Custom Hook은 코드의 재사용성을 높이기 위해 React의 Hook을 기반으로 사용자 정의 로직을 생성하는 것이다.

App.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import MyHook from './components/MyHook';

function App() {
  return (
    <div>
      <h1>Custom Hook Demo</h1>
      <MyHook />
    </div>
  );
}

export default App;

MyHook.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from 'react';
import useInputValue from '../hooks/useInputValue';

function MyHook() {
  const [value, bind, reset] = useInputValue('');

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Submitted value: ${value}`);
    reset();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" {...bind} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyHook;

useInputValue.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { useState } from 'react';

function useInputValue(initialValue) {
  const [value, setValue] = useState(initialValue);

  const reset = () => {
    setValue('');
  };

  const bind = {
    value,
    onChange: (e) => setValue(e.target.value),
  };

  return [value, bind, reset];
}

export default useInputValue;

Chapter 10: useEffect Demo

이 Chapter에서는 React의 useEffect Hook을 사용하여 컴포넌트 생명주기(lifecycle) 동안 특정 동작을 수행하는 방법을 설명한다. useEffect는 컴포넌트가 렌더링될 때, 업데이트될 때, 그리고 언마운트될 때의 로직을 정의할 수 있다.

App.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import MyComponent from './components/MyComponent';

function App() {
  return (
    <div>
      <h1>useEffect Demo</h1>
      <MyComponent />
    </div>
  );
}

export default App;

MyComponent.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;

    return () => {
      console.log('Cleanup on unmount or update');
    };
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default MyComponent;

이렇게 해서 Custom Hook과 useEffect Hook을 활용하는 방법에 대해 알아봤다. 이 내용들은 React에서 상태와 생명주기를 관리하는 데 중요한 개념들이다.

This post is licensed under CC BY 4.0 by the author.

© sseung. Some rights reserved.