Skip to content

Commit be29f9e

Browse files
committed
useEffect() explained
1 parent 2115895 commit be29f9e

File tree

5 files changed

+120
-46
lines changed

5 files changed

+120
-46
lines changed

MongoDB/populate-method-mongoose-referencing-other-model.md

+18-13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
##### `.populate()` is a way to populate referenced subdocuments in any schema.
2+
13
Lets take an example of a social network, one collection for users, and one for posts. In my research before doing any coding, I stumbled upon `Model.populate()`, a Mongoose method that you can use to essentially link documents across collections.
24

35
### Step 1: Make your schemas
@@ -32,6 +34,8 @@ module.exports = {
3234
};
3335
```
3436

37+
### Most simply - If you run this query: Post.find({}).populate('user').exec(callback), Mongoose will look at the field user in the post, see that it has a ref to the User model, and find that user by its \_id
38+
3539
This tells Mongoose “Hey, I’m gonna be referencing other documents from other collections”. The next part of that property is the ref (Post or User in the above code). The ref tells Mongoose “Those docs are going to be in the Post or User collection.”
3640

3741
So in our User schema, we reference the Post collection, because we want the user to be tied to the things they post, and we want to be able to easily access those posts without having to create more queries.
@@ -149,25 +153,26 @@ And in my Profile routes I have the following API endpoint
149153
150154
```js
151155
router.get(
152-
'/',
153-
passport.authenticate('jwt', { session: false }),
156+
"/",
157+
passport.authenticate("jwt", { session: false }),
154158
(req, res) => {
155159
const errors = {}; // just like in user route, I want to append to the errors object for any actual errors that will be generated. And returning that object for the error case
156160

157161
Profile.findOne({ user: req.user.id })
158-
.populate('user', ['name', 'avatar'])
162+
.populate("user", ["name", "avatar"])
159163
.then(profile => {
160164
if (!profile) {
161-
errors.noprofile = 'There is not profile for this user';
165+
errors.noprofile = "There is not profile for this user";
162166
return res.status(404).json(errors);
163167
}
164168
res.json(profile);
165169
})
166170
.catch(err => res.status(404).json(err));
167171
}
168-
)
172+
);
169173
```
170-
In the above A) I am populating my user's profile using the query builder. http://mongoosejs.com/docs/populate.html#population
174+
175+
In the above A) I am populating my user's profile using the query builder. http://mongoosejs.com/docs/populate.html#population
171176
172177
B) The first parameter of .populate() is the model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's 'ref' field.
173178
http://mongoosejs.com/docs/api.html#query_Query-populate
@@ -177,22 +182,22 @@ C) The second parameter to .populate() is the Field selection for the population
177182
D) Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). So, when I do the below
178183
179184
Profile.findOne({ user: req.user.id })
180-
.populate('user', ['name', 'avatar'])
185+
.populate('user', ['name', 'avatar'])
181186
182-
Populated paths are no longer set to their original _id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
187+
Populated paths are no longer set to their original \_id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
183188
(http://mongoosejs.com/docs/populate.html)
184189
185190
E) .populate() needs a query to attach itself to, so we are using Profile.findOne() to find a profile who matches the id I provide in the argument. This returns our user document. This is when .populate() takes over.
186191
187-
F) Flow of .populate() -> After findOne() finds the req.user.id and assigns it to the variable 'user' > .populate() is called on user, it will go to the appropriate collection (user model in this case) , search for that _ids, and return my user with 'name' and 'avatar'
192+
F) Flow of .populate() -> After findOne() finds the req.user.id and assigns it to the variable 'user' > .populate() is called on user, it will go to the appropriate collection (user model in this case) , search for that \_ids, and return my user with 'name' and 'avatar'
188193
189194
G) Why I can fetch user's model data with below line from profile route.
190195
191-
Profile.findOne({ user: req.user.id })
192-
.populate('user', ['name', 'avatar'])
196+
Profile.findOne({ user: req.user.id })
197+
.populate('user', ['name', 'avatar'])
198+
199+
Because - In Profile model, I have the the 'user' property as ObjectId
193200
194-
Because - In Profile model, I have the the 'user' property as ObjectId
195-
196201
### Sources to read
197202
198203
[https://medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7](https://mongoosejs.com/docs/2.7.x/docs/populate.html)

React/HOC.md

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
Intro
21
To put it simply, a higher-order component is a function, that takes a component and returns a new component. I like to think of them as parameterized components. Many times I find myself creating several components with very similar logic, with only 1 or 2 changes. Once I find a use case like this, it’s very simple to abstract the shared logic, and put the logic that changes into parameters.
32

43
You can read more about HOCs here, in the official React docs. Since components are just functions and HOCs are just functions that return other functions, we can use functional concepts to chain them using utilities methods such as compose, which is provided by many libraries (it's included in Redux!).

React/context-api-basics.md

+24-31
Original file line numberDiff line numberDiff line change
@@ -16,52 +16,39 @@ Material UI provides a snackbar component which is great for these types of mess
1616

1717
Many apps need to trigger messages from dozens of different components. The React Context API makes it dead simple to provide all components access to a shared snackbar so they can trigger these messages without needing to implement separate components for each message.
1818

19-
2019
### [How Do I Use Context?](https://hackernoon.com/how-do-i-use-react-context-3eeb879169a2)
2120

2221
[the codesandbox for this code](https://codesandbox.io/s/04l03y3q9v)
2322

2423
Prop Drilling
2524
I’ve built an application that stores a family’s last name in a <Grandmother /> component. The <Child /> component than displays the last name.
2625

27-
2826
```js
29-
const App = () => <Grandmother />
27+
const App = () => <Grandmother />;
3028

3129
class Grandmother extends React.Component {
3230
state = {
3331
lastName: "Sanchez"
34-
}
32+
};
3533

3634
render() {
37-
return <Mother lastName={this.state.lastName} />
35+
return <Mother lastName={this.state.lastName} />;
3836
}
3937
}
4038

4139
const Mother = ({ lastName }) => {
42-
return <Child lastName={lastName} />
43-
}
40+
return <Child lastName={lastName} />;
41+
};
4442

4543
const Child = ({ lastName }) => {
46-
return <p>{lastName}</p>
47-
}
44+
return <p>{lastName}</p>;
45+
};
4846
```
4947

5048
### Context
5149

5250
We can refactor this example to use Context instead. Using Context means we don’t need to pass the lastName through the <Mother /> component. We circumvent components that don’t need to know the lastName property, and share that state only with components that need to know it.
5351

54-
First, we will need to create our Context.
55-
56-
```js
57-
import React from "react";
58-
59-
const FamilyContext = React.createContext({});
60-
61-
export const FamilyProvider = FamilyContext.Provider;
62-
export const FamilyConsumer = FamilyContext.Consumer;js
63-
```
64-
6552
First, we will need to create our Context in a seperate file, say **FamilyContext.js**
6653

6754
```js
@@ -73,9 +60,9 @@ export const FamilyProvider = FamilyContext.Provider;
7360
export const FamilyConsumer = FamilyContext.Consumer;
7461
```
7562

76-
We use`` createContext()`` and pass it an empty object as the default value:
63+
We use`createContext()` and pass it an empty object as the default value:
7764

78-
``const FamilyContext = React.createContext({});``
65+
`const FamilyContext = React.createContext({});`
7966

8067
We then create a Provider and a Consumer component and export them so they are available for consumption by other components in your application.
8168

@@ -84,7 +71,7 @@ export const FamilyProvider = FamilyContext.Provider;
8471
export const FamilyConsumer = FamilyContext.Consumer;
8572
```
8673

87-
Here’s the final and full code of how we will use the Provider and Consumer in the Grandmother.js file
74+
Here’s the final and full code of how we will use the Provider and Consumer in the Grandmother.js file
8875

8976
```js
9077
import React from "react";
@@ -116,6 +103,7 @@ const Child = () => {
116103
return <FamilyConsumer>{context => <p>{context}</p>}</FamilyConsumer>;
117104
};
118105
```
106+
119107
Now, we have wrapped the <Mother /> component with <FamilyProvider /> because it contains <Child /> which is the component that needs access to the lastName prop.
120108

121109
```js
@@ -130,21 +118,25 @@ To actually have access to the lastName, we have also wrapped the <p> tag on lin
130118

131119
### Let’s dig a bit deeper into <FamilyConsumer />!
132120

133-
At first, it might look a bit confusing if you aren’t familiar with the render prop pattern, but with a bit of explanation I think you might find that it’s a fairly straightforward implementation. You don’t need to know how to build a render prop to use Context, but it’s a really powerful abstraction!
121+
At first, it might look a bit confusing if you aren’t familiar with the **[render prop](https://reactjs.org/docs/render-props.html)** pattern, but with a bit of explanation I think you might find that it’s a fairly straightforward implementation. You don’t need to know how to build a render prop to use Context, but it’s a really powerful abstraction!
134122

135123
### What’s a Render Prop?
136124

137-
A render prop is a way of writing components in React so that they are reusable, and can take n number of children of any type. Render props appear in a couple of different disguises. Context implements a Function as a Child Pattern, which is just a render prop called children.
125+
The term **“render prop”** refers to a technique for sharing code between React components using a prop whose value is a function.
126+
127+
A **render prop** is a way of writing components in React so that they are reusable, and can take n number of children of any type. Render props appear in a couple of different disguises. Context implements a Function as a Child Pattern, which is just a render prop called children.
138128

139129
```js
140130
const Child = () => {
141131
// Family Consumer uses the
142132
// Function as a Child pattern
143-
return <FamilyConsumer>
144-
// context is the object with lastName
145-
// on it. It gets passed as an argument
146-
{context => <p>{context}</p>}
147-
</FamilyConsumer>;
133+
return (
134+
<FamilyConsumer>
135+
// context is the object with lastName // on it. It gets passed as an
136+
argument
137+
{context => <p>{context}</p>}
138+
</FamilyConsumer>
139+
);
148140
};
149141
```
150142

@@ -153,11 +145,12 @@ const Child = () => {
153145
Ultimately, Context is a great tool to add to your React toolbox. Use it when you find prop drilling has become too complex, but your application isn’t large enough to warrant a third-party solution like MobX or redux.
154146

155147
### When Should I Use Context?
148+
156149
[https://hackernoon.com/how-do-i-use-react-context-3eeb879169a2](https://hackernoon.com/how-do-i-use-react-context-3eeb879169a2)
157150
I would recommend reaching for Context when you find yourself passing props down through three or more levels in your component tree. You might notice that you have renamed your props, making it challenging to determine the data’s origin. You might consider implementing context if a bunch of your components know about irrelevant data.
158151

159152
#### More References
160153

161154
1> [https://medium.com/dailyjs/reacts-%EF%B8%8F-new-context-api-70c9fe01596b](https://medium.com/dailyjs/reacts-%EF%B8%8F-new-context-api-70c9fe01596b)
162155

163-
2>
156+
2>

React/hooks-basics.md

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
**useEffect**
2+
3+
### you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
4+
5+
[https://reactjs.org/docs/hooks-effect.html](https://reactjs.org/docs/hooks-effect.html) - The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.
6+
7+
In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM.
8+
9+
This is why in React classes, we put side effects into componentDidMount and componentDidUpdate.
10+
11+
## Effects Without Cleanup {#effects-without-cleanup}
12+
13+
Sometimes, we want to **run some additional code after React has updated the DOM.** Network requests, manual DOM mutations, and logging are common examples of effects that don't require a cleanup. We say that because we can run them and immediately forget about them. Let's compare how classes and Hooks let us express such side effects.
14+
15+
### Example Using Classes {#example-using-classes}
16+
17+
In React class components, the `render` method itself shouldn't cause side effects. It would be too early -- we typically want to perform our effects _after_ React has updated the DOM.
18+
This is why in React classes, we put side effects into `componentDidMount` and `componentDidUpdate`. Coming back to our example, here is a React counter class component that updates the document title right after React makes changes to the DOM:
19+
20+
```js{9-15}
21+
class Example extends React.Component {
22+
constructor(props) {
23+
super(props);
24+
this.state = {
25+
count: 0
26+
};
27+
}
28+
componentDidMount() {
29+
document.title = `You clicked ${this.state.count} times`;
30+
}
31+
componentDidUpdate() {
32+
document.title = `You clicked ${this.state.count} times`;
33+
}
34+
render() {
35+
return (
36+
<div>
37+
<p>You clicked {this.state.count} times</p>
38+
<button
39+
onClick={() =>
40+
this.setState({ count: this.state.count + 1 })
41+
}
42+
>
43+
Click me
44+
</button>
45+
</div>
46+
);
47+
}
48+
}
49+
```
50+
51+
Note how **we have to duplicate the code between these two lifecycle methods in class.**
52+
This is because in many cases we want to perform the same side effect regardless of whether the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render -- but React class components don't have a method like this. We could extract a separate method but we would still have to call it in two places.
53+
Now let's see how we can do the same with the `useEffect` Hook.
54+
55+
### Example Using Hooks {#example-using-hooks}
56+
57+
We've already seen this example at the top of this page, but let's take a closer look at it:
58+
59+
```js{1,6-8}
60+
import React, { useState, useEffect } from "react";
61+
function Example() {
62+
const [count, setCount] = useState(0);
63+
useEffect(() => {
64+
document.title = `You clicked ${count} times`;
65+
});
66+
return (
67+
<div>
68+
<p>You clicked {count} times</p>
69+
<button onClick={() => setCount(count + 1)}>Click me</button>
70+
</div>
71+
);
72+
}
73+
```
74+
75+
**What does `useEffect` do?** By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our "effect"), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.
76+
**Why is `useEffect` called inside a component?** Placing `useEffect` inside the component lets us access the `count` state variable (or any props) right from the effect. We don't need a special API to read it -- it's already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.
77+
**Does `useEffect` run after every render?** Yes! By default, it runs both after the first render _and_ after every update. (We will later talk about [how to customize this](#tip-optimizing-performance-by-skipping-effects).) Instead of thinking in terms of "mounting" and "updating", you might find it easier to think that effects happen "after render". React guarantees the DOM has been updated by the time it runs the effects.

Redux/Store.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ A store is not a class. It's just an object with a few methods on it. To create
88

99
Check my working file - [https://github.com/rohan-paul/React-snippets/blob/master/redux-show-list-of-micro-blog-posts/src/store.js](https://github.com/rohan-paul/React-snippets/blob/master/redux-show-list-of-micro-blog-posts/src/store.js)
1010

11-
A store holds the whole state tree of my application. The only way to change the state inside it is to dispatch an action on it. A store is not a class. It's just an object with a few methods on it. To create it, pass your root reducing function to createStore.
11+
A store holds the whole state tree of my application. The only way to change the state inside it is to dispatch an action on it. A store is not a class. It's just an object with a few methods on it. To create it, pass your root reducing function to createStore.****

0 commit comments

Comments
 (0)