useRef() vs. const vs. useState()
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, useRef } = React;
// defined a variable outside function component
let countCache = 0;
function Counter() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
useEffect(() => {
// Update count on "after" every render
countCache = count;
countRef.current = count;
});
return (
<div>
<button onClick={() => setCount(p => p + 1)}>click me</button>
<h3>state {count}</h3>
<h3>variable {countCache}</h3>
<h3>reference {countRef.current}</h3>
</div>
);
}
function App() {
const [count, setCount] = useState(0);
const latestCount = useRef(count);
latestCount.current = count;
useEffect(() => {
setTimeout(() => console.log(latestCount.current), 5000);
}, []);
return (
<div>
{count}
<button onClick={() => setCount(count+1)}>+</button>
<button onClick={() => setCount(count-1)}>-</button>
<hr />
<Counter />
<Counter />
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#app"));