article ARTICLE
article4 min read

React: How to create and use custom hooks

Hooks are built-in functions in React that perform various tasks. The useState() hook, for example, is used to store and set values in the component, while the useEffect() hook causes the component to re-render if any of the values in the dependency array change, and so on.

A backend server isn’t required for simple SPAs that don’t contain complicated functionality. For example, if you design an app that tracks users’ salaries and expenses and calculates their taxes, the React app itself can do the math for you.

πŸ’‘ SPA = Single Page Application

But, because React is primarily a front-end framework, any backend logic doesn’t seem to fit into its architecture, and obviously you should avoid code smells like code duplication, etc — which is where custom hooks come in.

The major reason to utilize custom hooks in your application is when you need to develop modules with logic that generates valuable data. The output of the logic that is heavily correlated to the actual product is referred to as “valuable” here.If you filter out some elements from a data array, for example, you can utilize it in a component header:

❗️ THIS IS NOT PRODUCT LOGIC, THIS IS SIMPLE UI LOGIC

❗️ THIS IS NOT PRODUCT LOGIC, THIS IS SIMPLE UI LOGICconst Component = () => {  const data = fetched data...
  const filteredData = data.filter(item => item.id)  return(
    <div>
      {filteredData.map(item => (
        <p>{item.name}</p>
      ))}
    </div>
  )
}export default Component

However, if you need to get certain user data, such as incomes and expenses, and convert it to tax data, like in the example above, this will be product logic and you’ll need to use custom hooks.

To start, put your custom hooks in the architecture of your app. The ideal location for me is:

src/hooks

Now create your first custom hook file which will calculate taxes for you:

src/hooks/useTax.ts

We’ll be using TypeScript here, of course. Your custom hook will look like any other functional React file, except it won’t return JSX, it will return data.

πŸ’‘ JSX = JavaScript XML, it allows us to write HTML in React

The next step is to build useTax() hook’s basic frame:

βœ… THIS WILL BE YOUR PRODUCT LOGIC, SHOULD BE IN THE CUSTOM HOOKconst useTax = () => {
  type Taxes = {
    federal: number,
    medicare: number,
    socialSecurity: number
  }
  const [result, setResult] = useState<Taxes | null>(null)
  return result
}export default useTax

At this time, we have a fully functional custom hook. We can import and use it wherever we want, but it’s useless without data and logic, so let’s add some data and calculations:

βœ… THIS IS YOUR FINAL PRODUCT LOGIC, SHOULD BE IN THE CUSTOM HOOKconst useTax = () => {
  type Taxes = {
    federal: number,
    medicare: number,
    socialSecurity: number
  }
  const [result, setResult] = useState<Taxes | null>(null)  const incomes = fetch incomes...
  const expenses = fetch expenses...  useEffect(() => {
    if (!incomes || !expenses) return setResult(null)
    const federal = calculate federal tax...
    const medicare = calculate medicare tax...
    const socialSecurity = calculate social security tax...
    setResult({ federal, medicare, socialSecurity })
  }, [incomes, expenses])  return result
}export default useTax

That’s all there is to it. You can use your imported hook in any component on its own because it takes care of getting data, calculating different values, and updating them with useEffect().

βœ… NONE OF THE PRODUCT LOGIC IMPLEMENTED IN THE UI COMPONENTimport useTax from "../hooks/useTax"const Component = () => {  const taxes = useTax()  return(
    <div>
      <p>Federal tax: {taxes.federal} USD</p>
      <p>Medicare tax: {taxes.medicare} USD</p>
      <p>Social security tax: {taxes.socialSecurity} USD</p>
    </div>
  )}export default Component
1
  •  Inspiring
  • comment_icon  Comment