Skip to content

Commit 7ebd826

Browse files
committed
Add hooks questions and answers
1 parent 3f70eda commit 7ebd826

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,9 @@
315315
|299| [How to add a bootstrap for a react application?](#how-to-add-a-bootstrap-for-a-react-application)|
316316
|300| [Can you list down top websites or applications using react as front end framework?](#can-you-list-down-top-websites-or-applications-using-react-as-front-end-framework)|
317317
|301| [Is it recommended to use CSS In JS technique in React?](#is-it-recommended-to-use-css-in-js-technique-in-react)|
318+
|302| [Do I need to rewrite all my class components with hooks?](#do-i-need-to-rewrite-all-my-class-components-with-hooks)|
319+
|303| [How to fetch data with React Hooks?](#how-to-fetch-data-with-react-hooks)|
320+
|304| [Is Hooks cover all use cases for classes?](#is-hooks-cover-all-use-cases-for-classes)|
318321

319322
## Core React
320323

@@ -5030,4 +5033,37 @@
50305033
302. ### Do I need to rewrite all my class components with hooks?
50315034
No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.
50325035
303. ### How to fetch data with React Hooks?
5036+
The effect hook called `useEffect` is used to fetch the data with axios from the API and to set the data in the local state of the component with the state hook’s update function.
5037+
Let's take an example in which it fetches list of react articles from the API
5038+
```javascript
5039+
import React, { useState, useEffect } from 'react';
5040+
import axios from 'axios';
5041+
5042+
function App() {
5043+
const [data, setData] = useState({ hits: [] });
5044+
5045+
useEffect(async () => {
5046+
const result = await axios(
5047+
'http://hn.algolia.com/api/v1/search?query=react',
5048+
);
5049+
5050+
setData(result.data);
5051+
}, []);
5052+
5053+
return (
5054+
<ul>
5055+
{data.hits.map(item => (
5056+
<li key={item.objectID}>
5057+
<a href={item.url}>{item.title}</a>
5058+
</li>
5059+
))}
5060+
</ul>
5061+
);
5062+
}
5063+
5064+
export default App;
5065+
```
5066+
Remember we provided an empty array as second argument to the effect hook to avoid activating it on component updates but only for the mounting of the component. i.e, It fetches only for component mount.
5067+
304. ### Is Hooks cover all use cases for classes?
5068+
Hooks doesn't cover all use cases of classes but there is a plan to add them soon. Currently there are no Hook equivalents to the uncommon **getSnapshotBeforeUpdate** and **componentDidCatch** lifecycles yet.
50335069

0 commit comments

Comments
 (0)