It’s been half a year since the last article, and I’ve been obsessed with my work lately. I’ve been looking at the bullish position of the Nuggets every day. But the leader recently told me that you are using hooks a lot. Maybe do an in-group technology share. So I picked up my pen and wrote something like popularize Hooks
Having said that, I’ve moved away from using class components (unless some old project or function component support is not strong enough, like Taro wrote a small program) and instead embraced hooks, which make writing code much more efficient.
Based on my own practice and my understanding of hooks, it brings me the most:
- 1. Clearer component logic. Without some of the obscure features and pitfalls of lifecycle functions and classes, component rendering is just function execution
- 2. It provides a better way to reuse state logic
- 3. Cleaner code, smaller granularity of components and logic
React Hooks
I will now share with you how to write our code using hooks to implement our functionality by implementing one of the most common list pages with filters.
Page prototype(Photo credit: AlifeicingTemplate)unpkg.com/@icedesign/…
1. Use useState to initialize state
Use data and filters together with Immutable to hold list and filter data. The useState function argument is the initial state value.
import { fromJS } from 'immutable'; import { Table } from 'antd'; Function TablePage() {const [data, setData] = useState([]); const [data, setData] = useState([]); const [filters, setFilters] = useState(fromJS({ deliveryTime: [], orderTime: [], name: '', })); Return (<div> <Filters /> {/*Filters are specific Filters. */} <Table dataSource={data} /> </div>); }Copy the code
2. UseEffect to perform side effects
UseEffect is, in my opinion, the most important hooks that give us the means to implement various side effects after a component is rendered. UseEffect is componentDidMount, componentDidUpdate, and componentWillUnmount. So effect is executed after every render update, including the first.
This raises the question of how to control useEffect execution, so the second argument to useEffect comes into play at this point, providing a basis for whether or not useEffect is executed. Before using effect, React determines whether each dependency in the argument is the same as the last rendered value (===). If so, effect will be skipped.
UseEffect (() => {effect1(); } []); useEffect(() => { getData(); // Function to get data, depending on the value of filters}, [filters]);Copy the code
So our page code now looks like this:
function TablePage() { const [data, setData] = useState([]); const [filters, setFilters] = useState(fromJS({ deliveryTime: '', orderTime: '', name: '', })); useEffect(() => { getData(); // Function to get data, depending on the value of filters}, [filters]); FetchAPI ({deliveryTime: filters. Get ('deliveryTime'), orderTime: filters.get('orderTime'), name: filters.get('name'), }) .then((rsp) => { setData(rsp.data); }); } function handleFiltersChange(key, value) { setFilters(filters.set(key, value); } return (<div> <Filters onChange={handleFiltersChange} /> {/*Filters are specific filter components, } <Table dataSource={data} /> </div>); }Copy the code
3. Customize Hooks for logic reuse
In everyday development, we have a lot of logic that is actually repetitive, and when we want to share logic between two functions, we pull it into a third function. Components and hooks are functions, so the same applies. This third function is our custom Hook. A custom Hook is a function whose name starts with “use” and must begin with “use”; Other hooks can be called inside a function, and the hooks inside it are completely independent.
3.1 usePagination Implements paging logic
function usePagination(paginationOptions) { const [_pagination, setPagination] = useState(fromJS({ total: 0, current: 1, pageSize: 10, ... paginationOptions, })); return [_pagination, setPagination]; }Copy the code
3.2 useDebounce Implements request interface shock prevention
function useDebounce() {
const [timer, setTimer] = useState(0);
function debounce(throttleFunc, ThrottleTime = 250) {
clearTimeout(timer);
setTimer(setTimeout(throttleFunc, ThrottleTime));
}
return debounce;
}
Copy the code
We can use our custom hooks on the list page like this:
function TablePage() { const [data, setData] = useState([]); const [filters, setFilters] = useState(fromJS({ deliveryTime: '', orderTime: '', name: '', })); const [pagination, setPaination] = usePagination(); const debounce = useDebounce(); UseEffect (() => {debounce(getData); // Function to get data, depending on the value of filters}, [filters, pagination]); FetchAPI ({deliveryTime: filters. Get ('deliveryTime'), orderTime: filters.get('orderTime'), name: filters.get('name'), }) .then((rsp) => { setData(rsp.data); }); } function handleFiltersChange(key, value) { setFilters(filters.set(key, value); } function handleTableChange(_pagination) { setPaination( pagination.set('current', _pagination.current) .set('pageSize', _pagination.pageSize) ); } return (<div> <Filters onChange={handleFiltersChange} /> {/*Filters are specific filter components, */} <Table columns={/* wirte your own columns config */} dataSource={data} onChange={handleTableChange} /> </div>);Copy the code
To learn more about how to play with custom hooks, check out this article: In 2019, you will learn how to quickly migrate to the use of React Hooks. In my previous article on React Hooks, which included some use of useContext and useReducer, as well as some custom Hooks, you will learn how to use them.
4. To summarize
So we basically have a function component that is managed by Hooks. Maybe this simple list doesn’t fully capture the Hooks’ advantages, but there are optimizations like useMemo and useCallback with HOC, and the recent use of TypeScript. Finally, welcome everyone to give me suggestions, more exchanges, let us make progress together in nuggets!