Skip to content

Commit 3518b5f

Browse files
committed
Coding exercise for ref usage
1 parent 010b1b6 commit 3518b5f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

coding-exercise/README.md

+39
Original file line numberDiff line numberDiff line change
@@ -188,3 +188,42 @@ This issue can be fixed by wrapping the **<MyCustomInput />** component with `fo
188188
189189
**[⬆ Back to Top](#table-of-contents)**
190190
191+
#### 5. What is the outcome of number of clicks after 3 button clicks?
192+
193+
```javascript
194+
import { useRef } from 'react';
195+
196+
export default function Counter() {
197+
let ref = useRef(0);
198+
199+
function handleClick() {
200+
ref.current = ref.current + 1;
201+
}
202+
203+
return (
204+
<>
205+
<div>Clicked + {ref.current} + times</div>
206+
<button onClick={handleClick}>
207+
Click me!
208+
</button>
209+
</>
210+
);
211+
}
212+
```
213+
214+
- 1: 3 times
215+
- 2: 4 times
216+
- 3: 2 times
217+
- 4: 0 times
218+
219+
<details><summary><b>Answer</b></summary>
220+
<p>
221+
222+
##### Answer: 4
223+
If you try to use **{ref.current}** in the render method, the number won’t be updated on click. This is because **ref.current** does not trigger a re-render unlike state. This property is mainly used to read and write the values inside event handler or outside the render method.
224+
</p>
225+
</details>
226+
227+
---
228+
229+
**[⬆ Back to Top](#table-of-contents)**

0 commit comments

Comments
 (0)