Castore  DeRose

Castore DeRose


How to Build Custom React Hooks

React hooks simplify the process of creating reusable, clean and versatile code, and advanced optimization techniques like memoization are now more accessible and easier to use. React’s official documentation doesn’t cover custom hooks in detail as it covers the basic hooks, so the focus of this article is going to be primarily on building custom React hooks and best practices.

Understanding basic React hooks are required to get the most out of this article. If you aren’t already familiar with the basics, there are numerous great articles out there covering them. For example, React’s official docs are a great place to start.


In order to build a versatile, performant and reusable custom hook, there are several things to keep in mind.

Hooks run each time component re-renders

Since we’re working with functional components and hooks, we no longer have the need for lifecycle methods. Each time state or a prop is changed, the functional component is being re-rendered and, thusly, our custom hook is being called over and over again.

Use basic hooks as much as possible

Basic React hooks are the core of any custom hook. We can use memoizationand hook dependency arrays to control which parts of our custom hook will change or will not change with each re-render. It’s important to understand the role each basic hook can have in our custom hook in order to use them effectively and build performant hooks.

Rules of hooks

There are a few important rules to keep in mind. These rules are explained in detail on React hooks documentation.

Building the custom hook

Now that we have covered the basics, we’re ready to build our own custom hook. In the following example, we’ll establish a solid pattern for building custom hooks and go through some of the best practices.

Let’s imagine that we’re working on a project where users can play multiple games that use dice rolls as part of their game mechanic. Some games require only a single dice to play and some games may require multiple dice to play. We’ll also assume that during some games, the number of dice used may change.

Keeping that in mind, we are going to build useGameDice hook with the following features:

  • Custom hook can be initialized with the number of dice being used and an initial value
  • Function that sets the number of dice being used
  • Function that rolls the dice. Returns an array of random numbers between 1 and 6. Length is determined by the number of dice being used
  • Function that resets all dice values to initial value

Setting up the hook (imports and hook function)

We are declaring our custom hook as a regular arrow function using the recommended convention of naming custom hooks - the name should start with "use" keyword. We are also importing React hooks that we’ll use later on in our implementation. We could also import constants, other functions, other custom hooks, etc.

Our hook can be initialized with 2 optional variables:

  • initialNumberOfDice - how many dice will be used
  • initialDiceValue - determines the initial value and value after reset

Both variables have a default value of 1 to avoid any errors and simplify the hook setup.

import { useState, useMemo, useCallback, useEffect } from "react";

export const useGameDice = (initialNumberOfDice = 1, initialDiceValue = 1) => {
/* We’ll be adding code here in order */

Adding state and memoized private variables

First, we need to set up our state. We’ll declare two simple states:

  • diceValue - array which size is defined by numberOfDice and holds value for each dice
  • numberOfDice - determines the number of dice (diceValue array size) that will be used

We are also initializing initialDiceState variable that creates the initial array value that will be assigned on initial render and state reset. This value is memoized to avoid array being initialized and filled with default values on each re-render.

 const [diceValue, setDiceValue] = useState();
const [numberOfDice, setNumberOfDice] = useState(initialNumberOfDice);

const initalDiceState = useMemo(
() => Array(numberOfDice).fill(initialDiceValue),
[numberOfDice, initialDiceValue]

Adding memoized hook functions

Next, we’ll create the following functions:

  • generateRandomDiceNumber - generates a random number between 1 and 6 (a single dice roll)
  • rollDice - calls a random number generator for each element in the array (dice)
  • resetDice - resets the dice value state to an initial value
const generateRandomDiceNumber = useCallback(() => {
return Math.floor(Math.random() * 6) + 1;
}, []);

const rollDice = useCallback(() => {
const arrayConfig = { length: numberOfDice };
const newDiceValues = Array.from(arrayConfig, generateRandomDiceNumber);
}, [numberOfDice, generateRandomDiceNumber]);

const resetDice = useCallback(() => {
}, [initalDiceState]);

We are using useCallback hook to control when the functions are going to be re-initialized. Functions are re-initialized only when any variable in their dependency array changes. In case of the generateRandomDiceNumberfunction, it’s never re-initialized after the first render and initialization because this function doesn’t depend on any external variable or state.

Adding side effects - hook initialization & update

We need to set up a listener that will watch for updates to our initial dice state. This side effect has two responsibilities:

  1. It sets the dice state to the initial value when the hook is first initialized
  2. It updates the dice state to the initial value when dice number (array size) has changed
 useEffect(() => {
}, [initalDiceState]);

API setup & return statement

Finally, we are defining our state and api objects and returning them in an array, following the useState convention. Let’s take a look at each object:

  • state - holds all our state values. We expect this object to change on almost every re-render
  • api - holds all functions. We are returning some of our functions declared in useCallback and a function from useState hook. This object is memoized because we do not expect this to change on almost every re-render
const state = {

const api = useMemo(
() => ({
[setNumberOfDice, rollDice, resetDice]

return [state, api];

We are returning the objects in an array because we want this hook to be flexible. By doing so, we allow developers to rename the returned variables and allow them to initialize multiple instances of this hook if needed.

 const [diceFirst_state, diceFirst_api] = useGameDice();
const [diceSecond_state, diceSecond_api] = useGameDice();

Git repository & demo

You can see the final implementation and full code with a demo on the following GitHub repository.

React custom hooks pattern overview

By now, you might have noticed that we grouped the code we were adding in sections. This structured and clean pattern follows a logical path:

  1. State initialization (useState, useReducer), local variables initialization (useMemo), ref initialization (useRef) & external custom hooks initialization
  2. Memoized functions (useCallback)
  3. Side effects (useEffect)
  4. API setup (state and memoized api)
  5. Return statement


It’s no surprise that hooks were well received by React community. Developers are able to share logic between components more easily, create multiple components (interfaces) for each custom hook, pick and choose the parts of hook’s state and API they’ll use in their components, etc.

This reusability and versatility make hooks a real game-changer in React app development. With an established pattern and best practices when building custom React hooks, developers are able to deliver code with consistent quality, clear structure, and optimal performance.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Further reading

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ How To Write Better Code in React

☞ React Router: Add the Power of Navigation

☞ Getting started with React Router

☞ Using React Router for optimizing React apps

☞ Creating RESTful APIs with NodeJS and MongoDB Tutorial

Originally published on

#reactjs #react-native #web-development

What is GEEK

Buddha Community

How to Build Custom React Hooks
Autumn  Blick

Autumn Blick


How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:-

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

How to Fix Memory Leaks with a Simple React Custom Hook

See error logs in your console with the message “Cannot perform state update on an unmounted component” from your React application? There is a simple cause and easy fix.

The Cause

React components which run asynchronous operations and perform state updates can cause memory leaks if state updates are made after the component is unmounted. Here is a common scenario where this could pop up:

  1. User performs an action triggering an event handler to fetch data from an API.
  2. The user clicks on a link, navigating them to a different page, before (1) completes.
  3. The event handler from (1) completes the fetch, and calls a state setter function, passing it the data that was retrieved from the API.

Since the component was unmounted, a state setter function is being called in a component that is no longer mounted. Essentially, the setter function is updating state no longer exists. Memory Leak.

Here is a contrived example of unsafe code:

const [value, setValue] = useState({});
useEffect(() => {
    const runAsyncOperation = () => {
        setTimeout(() => {
            setValue({ key: 'value' });
        }, 1000);
    // IN LESS THAN 1000 MS
}, []); 

#web-development #react #javascript #react-hook #custom-react-hook

Hayden Slater


Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

Erna  Herzog

Erna Herzog


Build a React Accordion from Scratch Using React Hooks and No Extra Dependencies

Follow these step-by-step instructions to create an animated accordion component in React.js using React Hooks and CSS.



React DOM Elements:

Overview of dangerouslySetInnerHTML:

How to prevent XSS attacks when using dangerouslySetInnerHTML in React:

Hooks API Reference:

Visual Studio Code:

#react #react hooks #react accordion #css #react.js