Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Member-only story

4 Custom React Hooks Every Developer Should Know

5 min readJun 14, 2024

--

Press enter or click to view image in full size
Photo by Lautaro Andreani on Unsplash

My friends, if I had learned these 4 React hooks earlier, maybe I could have written more beautiful code.

They greatly improved my work efficiency and the scalability and readability of my code. You must want to learn them too?

1. useMount

In the past, I often wrote this style of code, and when the component was first rendered, I needed to send a request or do some other logic, probably like this.

useEffect(() => {
// fetch request...
}, [])

That’s pretty simple, isn’t it? But it has one big disadvantage: The semantics are not clear enough, even if we pass in an empty array.

So we can customize a hook called useMount to execute the callback function only when the component is first rendered.

Source code

const useMount = (callback) => {
React.useEffect(callback, [])
}

Example

const UseMountDemo = () => {
const [count, setCount] = React.useState(0)

useMount(() => {
console.log("useMount")
})

return (
<div>
count: { count }
<button onClick={() => setCount(count++)}>add</button>
</div>…

--

--

fatfish
fatfish

Written by fatfish

Hi friends, I am a front-end engineer from Alibaba, let’s code happily together.

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.