Skip to content

Commit 06a5e70

Browse files
committed
preventDefault() in React
1 parent 4258a9e commit 06a5e70

File tree

2 files changed

+179
-0
lines changed

2 files changed

+179
-0
lines changed

React/Hooks/useRef-basics.md

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#### When to use useRef
2+
3+
##### First Explanation -
4+
5+
In plain JavaScript you had to use **getElementById** or **querySelector** to select a DOM node.
6+
7+
But this is not an ideal solution in React.
8+
9+
In React you want to use the useRef hook or if you’re in a React class component, you want to use createRef.
10+
11+
The reason you don’t want to use **getElementById** or **querySelector** is because you may be designing your React app to output multiple of the same ID’s, which is a no no.
12+
13+
Another reason to use useRef is because it helps with the unidirectional (single direction) data flow.
14+
15+
You can define a node reference in a parent component and toss them down to child components.
16+
17+
Hence the single direction data flow.
18+
19+
```js
20+
// Old reference method
21+
const inputRef = document.querySelector('input')
22+
23+
// React hooks way
24+
const inputRef = useRef()
25+
26+
<input ref={inputRef}>
27+
28+
```
29+
30+
React will than give you a an object with a property called current.
31+
32+
Per official doc - useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
33+
34+
The value of current is an object that represents the DOM node you’ve selected to reference.
35+
36+
You should avoid using reference calls as much as possible. There are only 3 good reasons why you’d need to use the useRef hook.
37+
38+
Managing focus, text selection, or media playback
39+
Triggering imperative animations
40+
Integrating with third-party DOM libraries
41+
42+
Refs are used to access DOM or React elements rendered in the render function. And the standard way of using refs in previous React versions was something like this
43+
44+
```js
45+
class MyComponent extends React.Component {
46+
constructor(props) {
47+
super(props);
48+
this.myRef = React.createRef();
49+
}
50+
51+
render() {
52+
return <div ref={this.myRef} />;
53+
}
54+
}
55+
```
56+
57+
And to have access to the current node -
58+
59+
`const node = this.myRef.current;`
60+
61+
Now with new hooks api **useRef**
62+
63+
```js
64+
import React, { useRef } from "react";
65+
66+
function UnderstandRefHooks() {
67+
// create refs
68+
const inputRef = useRef();
69+
70+
const handleChange = () => {
71+
console.log(inputRef.current);
72+
};
73+
74+
return (
75+
<div>
76+
<input onChange={handleChange} ref={inputRef} />
77+
</div>
78+
);
79+
}
80+
```
81+
82+
##### Second Explanation -
83+
84+
The useRef hook is pretty powerful and often can be abused. In general, developers should avoid using useRef if they could use useState instead.
85+
86+
```js
87+
import React, { useEffect, useRef } from "react";
88+
89+
const GoodCounter = () => {
90+
const count = useRef(0);
91+
let currentCount = count.current;
92+
93+
useEffect(() => {
94+
count.current = currentCount;
95+
});
96+
97+
currentCount += 1;
98+
99+
return <div>count:{currentCount}</div>;
100+
};
101+
102+
export default GoodCounter;
103+
```
104+
105+
This code uses useEffect, whose first argument function is only invoked in the commit phase. The currentCount is a local variable within the render function scope, and it will only change the ref count in the commit phase. The ref is essentially a global variable outside the function scope, hence modifying it is a side effect.
106+
107+
By Dan himself - **useRef() is basically useState({current: initialValue })[0]**
108+
109+
##### Third Explanation -
110+
111+
[https://www.codebeast.dev/usestate-vs-useref-re-render-or-not/](https://www.codebeast.dev/usestate-vs-useref-re-render-or-not/)
112+
113+
- useState causes re-render; useRef does not.
114+
- Both useState and useRef remembers their data after a re-render
115+
116+
#### Further Reading
117+
118+
- 1. [https://reactjs.org/docs/hooks-reference.html#useref](https://reactjs.org/docs/hooks-reference.html#useref)
119+
- 2. [https://medium.com/@dai_shi/how-to-properly-use-the-react-useref-hook-in-concurrent-mode-38c54543857b](https://medium.com/@dai_shi/how-to-properly-use-the-react-useref-hook-in-concurrent-mode-38c54543857b)

React/preventDefault-in-React.md

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#### What is preventDefault() in React?
2+
3+
React uses synthetic events to handle events from button, input and form elements. A synthetic event is a shell around the native DOM event with additional information for React.
4+
5+
Lets see the code where
6+
7+
- A> Initially I have a list as an array 'initialList'
8+
- B> And then add an item to that list by using a form element with input and button elements.
9+
- C> In this case, a preventDefault is called on the event when submitting the form to prevent a browser reload/refresh.
10+
-
11+
12+
```js
13+
import React from "react";
14+
15+
const initialList = ["Learn React", "Learn Firebase", "Learn GraphQL"];
16+
17+
const ListWithAddItem = () => {
18+
const [value, setValue] = React.useState("");
19+
const [list, setList] = React.useState(initialList);
20+
21+
const handleChange = event => {
22+
setValue(event.target.value);
23+
};
24+
25+
const handleSubmit = event => {
26+
if (value) {
27+
setList(list.concat(value));
28+
}
29+
30+
setValue("");
31+
32+
event.preventDefault();
33+
};
34+
35+
return (
36+
<div>
37+
<ul>
38+
{list.map(item => (
39+
<li key={item}>{item}</li>
40+
))}
41+
</ul>
42+
43+
<form onSubmit={handleSubmit}>
44+
<input type="text" value={value} onChange={handleChange} />
45+
<button type="submit">Add Item</button>
46+
</form>
47+
</div>
48+
);
49+
};
50+
51+
export default ListWithAddItem;
52+
```
53+
54+
Why is a form submit reloading the browser? All native HTML elements come with their internal native behavior. For instance, input elements store their internal state. That’s why often React is used to take over for having controlled components by managing the state via React. The same applies for a form element which has a submit event that is invoked via a submit button element. In the past, it was desired to refresh the browser to flush all state and to submit the data to a backend. Nowadays, a library such as React, gives us more flexibility to deal with the submit event ourselves. In this case, we deal with it by updating the list in our component’s state.
55+
56+
In another scenario, you may fetch data from a backend and store it in your component’s state. There is no native submission from the form expected anymore, that’s why the developer is able to take over. The developer shouldn’t need to worry about any undesired behavior of the browser.
57+
58+
#### Reading
59+
60+
- [https://www.robinwieruch.de/react-preventdefault/](https://www.robinwieruch.de/react-preventdefault/)

0 commit comments

Comments
 (0)