Skip to content

Commit

Permalink
Add useRef examples
Browse files Browse the repository at this point in the history
  • Loading branch information
clarkdo committed Aug 6, 2020
1 parent 47704d9 commit 84ac156
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 1 deletion.
Empty file removed src/UseReducer2.js
Empty file.
30 changes: 30 additions & 0 deletions src/UseRef1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React, { useState } from "react";
import "./styles.css";

function Counter() {
const [count, setCount] = useState(1);

return (
<div>
<h2>You clicked {count} times</h2>
<button
onClick={() => {
setTimeout(() => {
setCount(count + 1);
}, 1000);
}}
>
Increment
</button>
</div>
);
}

export default function App() {
return (
<div className="App">
<h1>Without useRef</h1>
<Counter />
</div>
);
}
39 changes: 39 additions & 0 deletions src/UseRef2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React, { useEffect, useRef, useState } from "react";
import "./styles.css";

const usePrevious = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref;
};

function Counter() {
const [count, setCount] = useState(1);
const prevCountRef = usePrevious(count);

return (
<div>
<h2>You clicked {count} times</h2>
<button
onClick={() => {
setTimeout(() => {
setCount(prevCountRef.current + 1);
}, 1000);
}}
>
Increment
</button>
</div>
);
}

export default function App() {
return (
<div className="App">
<h1>Without useRef</h1>
<Counter />
</div>
);
}
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@ import UseMemo1 from "./UseMemo1";
import UseMemo2 from "./UseMemo2";
import UseState1 from "./UseState1";
import UseState2 from "./UseState2";
import UseRef1 from "./UseRef1";
import UseRef2 from "./UseRef2";

const rootElement = document.getElementById("root");
ReactDOM.render(
<>
{/* <UseCallback1 /> */}
{/* <UseCallback2 /> */}
{/* <UseMemo1 /> */}
<UseMemo2 />
{/* <UseMemo2 /> */}
{/* <UseState1 /> */}
{/* <UseState2 /> */}
{/* <UseRef1 /> */}
<UseRef2 />
</>,
rootElement
);

0 comments on commit 84ac156

Please sign in to comment.