Muscardinus

Custom Hooks 예시 본문

FrontEnd/React Basics

Custom Hooks 예시

Muscardinus 2021. 2. 13. 16:39
728x90
import React, { useEffect } from 'react';
import useLocalStorage from './useLocalStorage';

export default function Test() {
  const [name, setName] = useLocalStorage('name', '');
  return (
    <input type='text' value={name} onChange={(e) => setName(e.target.value)} />
  );
}

 

import { useState, useEffect } from 'react';

const getSavedValue = (key: string, initialValue: string) => {
  const savedValue = JSON.parse(localStorage.getItem(key) as string);
  if (savedValue) return savedValue;
  return initialValue;
};

export default function useLocalStorage(
  key: string,
  initialValue: string
): [string, React.Dispatch<string>] {
  const [value, setValue] = useState<string>(() =>
    getSavedValue(key, initialValue)
  );

  useEffect(() => {
    console.log('MOUNTED');
  }, []);

  useEffect(() => {
    console.log('CHANGE');
    localStorage.setItem(key, JSON.stringify(value));
  }, [value, key]);
  return [value, setValue];
}

 

 

 

 

 

 

728x90

'FrontEnd > React Basics' 카테고리의 다른 글

useSelector에서 성능 최적화  (0) 2021.06.20
React 성능 최적화 체크리스트  (0) 2021.05.23
useState 초기값  (0) 2021.02.13
setState에서 async를 사용해도 될까?  (0) 2020.12.26
Props & Event  (0) 2020.10.13
Comments