React provids a variety of hooks developer can use. However, some developers want to make custom hook which they need in specific case.
So, On this post I introduce how to make custom hook on React project.
1. Original code
import logo from './logo.svg';
import './App.css';
import React, { useReducer } from 'react';
import { useDebugValue, forwardRef, useImperativeHandle, useState, useEffect, useRef, useMemo, useCallback, memo} from 'react';
import Timer from './component/Timer.js';
import Page from './component/Page.jsx'
import {ThemeContext} from './context/ThemeContext.js'
import { useInput } from './component/useInput.js';
function App() {
const [inputValue, setInputValue] = useState();
const handleChange = (e) => {
console.log("handleChange ", e.target.value)
setInputValue(e.target.value)
}
const handleSubmit = () => {
console.log("handleSubmit ", inputValue)
alert(inputValue)
setInputValue("")
}
return (
<>
<div>
<h1>useInput</h1>
<input value={inputValue} onChange={handleChange}/>
<button onClick={handleSubmit}>OK</button>
</div>
</>
)
}
export default App;
This is simple code to receive user's input value and show alert when user clicks button.
Let's make custom hook and push common code onto custom hook.
2. Custom Hook : useInput.js
import React, { useReducer } from 'react';
import { useDebugValue, forwardRef, useImperativeHandle, useState, useEffect, useRef, useMemo, useCallback, memo} 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]
}
Custom Hook named useInput has useState hook, handleChange method and handleSubmit method.
So, when we write code, we don't need to write these kind of code repetitively.
3. App.js using Custom Hook
import logo from './logo.svg';
import './App.css';
import React, { useReducer } from 'react';
import { useDebugValue, forwardRef, useImperativeHandle, useState, useEffect, useRef, useMemo, useCallback, memo} from 'react';
import Timer from './component/Timer.js';
import Page from './component/Page.jsx'
import {ThemeContext} from './context/ThemeContext.js'
import { useInput } from './component/useInput.js';
function displayMessage(message){
alert(message)
}
function App() {
const [inputValue, handleChange, handleSubmit] = useInput("", displayMessage)
return (
<>
<div>
<h1>useInput</h1>
<input value={inputValue} onChange={handleChange}/>
<button onClick={handleSubmit}>OK</button>
</div>
</>
)
}
export default App;
Because of Custom Hook, code get simpler.
0 댓글