React Custom Hooks using useEffect()

by cadenzah

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}

Babel + JSX

const { useState, useEffect, useMemo, useCallback } = React;

function useCustomHook(initialValue, identifier) {
	console.log(`running useCustomHook - ${identifier}`);
	const [count, setCount] = useState(initialValue);
  
	useEffect(() => {
  	console.log(`useCustomHook\'s useEffect - ${identifier}`);
    
    return () => {
	  	console.log(`useCustomHook\'s clean-up - ${identifier}`)
    };
  }, [count, setCount]);
  
  return [count, setCount];
}



function App() {
	console.log('running App.jsx');
  
  const [count,setCount] = useCustomHook(0, '1st');
  const [count2, setCount2] = useCustomHook(0, '2nd');
  
	return (
    <div>
      <div>1st - {count}</div>
      <button onClick={(e) => setCount(count + 1)}>+</button>
      <button onClick={(e) => setCount(count - 1)}>-</button>
      <div>2nd - {count2}</div>
      <button onClick={(e) => setCount2(count2 + 1)}>+</button>
      <button onClick={(e) => setCount2(count2 - 1)}>-</button>
    </div>
  )
}

ReactDOM.render(<App />, document.querySelector("#app"))