|
315 | 315 | |299| [How to add a bootstrap for a react application?](#how-to-add-a-bootstrap-for-a-react-application)|
|
316 | 316 | |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)|
|
317 | 317 | |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)| |
318 | 321 |
|
319 | 322 | ## Core React
|
320 | 323 |
|
|
5030 | 5033 | 302. ### Do I need to rewrite all my class components with hooks?
|
5031 | 5034 | 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.
|
5032 | 5035 | 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. |
5033 | 5069 |
|
0 commit comments