Hook is a new feature added in React16.8. Although the React official documentation has explained the relevant concepts of React hooks, it is difficult to use hooks well just by reading the official documentation. It is easy to fall into traps and errors when writing hooks. This article summarizes 5 bad places. 01. Use useState when render is not required In function components, we can use Not recommended× function ClickButton(props){ const [count, setCount] = setState(0) const onClickCount = () => { setCount((c) => c + 1) } const onClickRequest = () => { apiCall(count) } return ( <div> <button onClick={onClickCount}>Click</button> <button onClick={onClickRequest}>Submit</button> </div> ) } The problem: Looking carefully at the code above, at first glance there is nothing wrong with it. Clicking the button updates Recommended√ function ClickButton(props){ const count = useRef(0) const onClickCount = () => { count.current++ } const onClickRequest = () => { apiCall(count.current) } return ( <div> <button onClick={onClickCount}>Click</button> <button onClick={onClickRequest}>Submit</button> </div> ) } 02. Use router.push instead of link In React SPA applications, we use Not recommended× function ClickButton(props){ const history = useHistory() const onClickGo = () => { history.push('/where-page') } return <button onClick={onClickGo}>Go to where</button> } The problem: Although the above code works, it does not meet the requirements of Accessibility. The button will not be recognized as a link by the screen reader. Therefore, we can transform the code as follows: Recommended√ function ClickButton(props){ return <Link to="/next-page"> <span>Go to where</span> </Link> } 03. Handle actions with useEffectSometimes, we just want to run some additional code after React updates the DOM. For example, sending network requests, manually changing DOM, and recording logs. Not recommended× function DataList({ onSuccess }) { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [data, setData] = useState(null); const fetchData = () => { setLoading(true); callApi() .then((res) => setData(res)) .catch((err) => setError(err)) .finally(() => setLoading(false)); }; useEffect(() => { fetchData(); }, []); useEffect(() => { if (!loading && !error && data) { onSuccess(); } }, [loading, error, data, onSuccess]); return <div>Data: {data}</div>; } The problem: The above code uses two Recommended√ function DataList({ onSuccess }) { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [data, setData] = useState(null); const fetchData = () => { setLoading(true); callApi() .then((res) => { setData(res) onSuccess() }) .catch((err) => setError(err)) .finally(() => setLoading(false)); }; useEffect(() => { fetchData(); }, []); return <div>Data: {data}</div>; } 04. Single Responsibility ComponentWhen should you split a component into several smaller components? How to build component tree? All of these issues arise every day when using component-based frameworks. However, a common mistake when designing components is to combine two use cases into one component. Not recommended× function Header({ menuItems }) { return ( <header> <HeaderInner menuItems={menuItems} /> </header> ); } function HeaderInner({ menuItems }) { return isMobile() ? <BurgerButton menuItems={menuItems} /> : <Tabs tabData={menuItems} />; } The Problem: With this approach, the Recommended√ Moving the condition up one level makes it easier to see the purpose of the components and that they only have one responsibility, being either function Header(props) { return ( <header> {isMobile() ? <BurgerButton menuItems={menuItems} /> : <Tabs tabData={menuItems} />} </header> ) } 05. Single Responsibility useEffects By comparing Not recommended× function Example(props) { const location = useLocation(); const fetchData = () => { /* Calling the api */ }; const updateBreadcrumbs = () => { /* Updating the breadcrumbs */ }; useEffect(() => { fetchData(); updateBreadcrumbs(); }, [location.pathname]); return ( <div> <BreadCrumbs /> </div> ); } The problem: Recommended√ Separate two side effects from one useEffect. function Example(props) { const location = useLocation(); const fetchData = () => { /* Calling the api */ }; const updateBreadcrumbs = () => { /* Updating the breadcrumbs */ }; useEffect(() => { fetchData(); updateBreadcrumbs(); }, [location.pathname]); return ( <div> <BreadCrumbs /> </div> ); } refer to:Five common mistakes writing react components (with hooks) in 2020 The above are the details of the five things you need to pay attention to when using hooks to write React components. For more information about hooks to write React components, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Detailed explanation of Nginx static service configuration (root and alias instructions)
>>: MySQL 5.6.27 Installation Tutorial under Linux
In order to improve user experience and ease of us...
First, perform a simple Docker installation. To c...
<br /> Focusing on the three aspects of text...
Idea imports an existing web project and publishe...
1. What is it? MySQL is the most popular relation...
When I first came into contact with HTML, I alway...
1. MYSQL installation directory Copy the code as ...
Related articles: Install Docker using yum under ...
When making a website, I found that video files, s...
1. Add a comment block at the beginning of the sty...
Preface After reading the previous article about ...
Overview The builder pattern is a relatively simp...
In this article, we will analyze the production of...
The basic principle of all animations is to displ...
Table of contents Achieve results Implementation ...