Preface
react16.8 launches hooks to better support function components, using function components is easier to reuse code and has stronger scalability.
useState
useState is similar to the state function of the class component, used to update views
import React, { Component, useState } from 'react'; export default function Hello() { const [count, setCount] = useState(0); //Set the default value to 0 return <div> {count} <button onClick={()=>setCount(count + 1)}>Increase</button> </div> } //useState can also be assigned using functions const [count, setCount] = useState(()=>0); //Set the default value to0
useEffect
useEffect accepts two parameters. The first parameter is the callback function to be executed, and the second parameter is the dependent parameter. For example, in the following example, count will be printed only when the count changes. When the second parameter is an empty array, the component will execute once after the rendering is completed. When the second parameter is not passed, it will be executed every time the rendering is performed.
export default function Hello() { const [count, setCount] = useState(() => 0); //Set the default value to 0 // useEffect useEffect(() => { }, [count]) return <div> {count} <button onClick={() => setCount(count + 1)}>Increase</button> </div> }
UseEffect with return value is used to clear side effects during execution
useEffect(()=>{ const timer = setInterval(() => { (count); }, 1000); ('resize',handleResize); return function(){ clearInterval(timer); ('resize',handleResize); } }, [count])
If a timer is defined every time you execute useEffect, then more and more timers will be added, and this side effect is cancelled by clearing the timer in the return function. The execution time of the useEffect return function is before the next useEffect execution.
This can be used to achieve anti-shake and throttling functions
Get data
Here is the most basic way to get data in function components:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({ hits: [] }); useEffect(async () => { const result = await axios( '/api/v1/search?query=redux', ); setData(); }); return ( <ul> {(item => ( <li key={}> <a href={}>{}</a> </li> ))} </ul> ); } export default App;
The hook of useEffect is used to get data requested from the backend from the API and set data in the local state of the component using the update function of the state hook. prmomise parsing occurs asynchronous/waiting.
However, when you run the application, you will find that the effect hook runs when the component is loaded, but also when the component is updated, so it will fetch the data again and again. This is a mistake that needs to be avoided. We just want to get the data when the component is mounted. This is why you can provide an empty array as the second parameter of the effect hook to avoid activate it when the component is updated:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({ hits: [] }); useEffect(async () => { const result = await axios( '/api/v1/search?query=redux', ); setData(); }, []); return ( <ul> {(item => ( <li key={}> <a href={}>{}</a> </li> ))} </ul> ); } export default App;
The second parameter can be used to define all variables (assigned in this array) on which the hook depends. If one of the variables changes, the mount will run again. If the array containing variables is empty, the hook is not run at all when updating the component, because it does not have to monitor any variables.
There is one last question. In the code, we use async/await to get data from a third-party API. And we know that the async function returns an AsyncFunction object. However, the effect hook should not return anything or clean up functions. This is why it is not allowed to use asynchronously directly in effect hooks. Let's implement its solution by calling an asynchronous function inside effect:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({ hits: [] }); useEffect(() => { const fetchData = async () => { const result = await axios( '/api/v1/search?query=redux', ); setData(); }; fetchData(); }, []); return ( <ul> {(item => ( <li key={}> <a href={}>{}</a> </li> ))} </ul> ); } export default App;
This is how to use the React hook to get the data.
This is the article about the implementation method of React Hooks to obtain data. For more related React Hooks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!