Joseph  Norton

Joseph Norton


The React Custom Hooks Guide - Tutorials and Examples


React introduced hooks in the v16.8 release and they’re just plain fantastic! They’ve enabled developers to extract business logic out from components that weren’t otherwise possible with class-based components. This not only made the code shorter and cleaner but also provisioned for the sharing of logic and not just UI components in react code. If you’re new to hooks and want to learn more about them, head over to the official documentation.

React has extracted a lot of its functionalities out as hooks - state, effects (component lifecycle methods, basically), refs, context and much more. But, along with all this, they also allow developers to use multiple of these and compose their own hooks - Custom Hooks; and that’s what the focus of this article is on :)

Let’s learn to create and test custom hooks with the following example

Problem Statement

We need to create an input component that fetches its default value using an API call. Once this is done, thee user can choose to modify the content in the input field. Why do we need hooks for this, you ask? HTML5 provides a defaultValue API for input tags. However, we cannot use that as the defaultValue is used only while mounting the input element. Once the element is mount, we cannot pass a defaultValue.

Since we don’t know when the API call will be completed, we cannot rely on defaultValue. We need to store a value in the state, make an API call when the component mounts and update the state once the API call succeeds. Everytime the user updates thee value in the input, update value in the state. As we’re not using class-based components, we cannot use the older state and lifecycle methods. We need hooks!

Since our application needs to make an API call, I’ve hosted the below JSON using the []( free JSON hosting service. We will be making our API call to this endpoint to get the default value.

  "defaultValue": "test"

Let’s build the useInput custom hook using useState to maintain the value of the input in the state and the useEffect to make the API call on mount

import {
} from 'react';export const useInput = () => {
    const [value, setValue] = useState('');
    useEffect(() => {
            .then((data) => data.json())
            .then((data) => setValue(data.defaultValue))
    }, []);
    return [value, setValue];
}export default useInput;

The useEffect serves to replace both componentDidMount and componentDidUpdate. In order to run the function only when the component is mount, we need to tell it that it does not need to ‘spy’ on any data values. We do this by passing the optional second parameter to useEffect, an empty array.

As you can see above, our hook does three things:
1. Initialises the state with an empty string value.
2. fetches the data from the API to set the defaultValue in the state
3. Provides an interface (setValue) for the user to edit the value.

Let’s try it out

To check if our hook works, we need to create an input component that would use the hook we just created.

import {useInput} from './path/to/useInput';const Input = () => {
    const [value, setValue] = useInput();
    return (
        onChange={(e) => setValue(}
    );}export default Input;

When you render the Input component in your app, you should see something like this:

React Custom Hooks Guide

Testing the hook

Since hooks are, in essence, just functions, you’d imagine that we could directly test them like we do with other pure functions. However, that is not the case. React enforces the use of hooks only inside functional components or other custom hooks. If we try calling a hook as a function normally, we get an error.

Hence, we need to somehow create a test component that would internally use our hook and return the state (if any). Sounds complicated? luckily this awesome human being called Kent C Dodds has developed a library called react-testing-library. It contains many features to do normal unit testing for react components but it also provides a richer version of the new “test component” that we just spoke of. So before we start, install the below packages:

npm install --save-dev @testing-library/react @testing-library/react-hooks react-test-renderer

The first two packages are the react-testing-library packages and thee last, react-test-renderer is the renderer used by react-testing-library .

To begin our tests, we need to first mock the global fetch object. We can do this by using the jest.spyOn method.

// useInput.test.jsdescribe('the useInput hook', () => {
    beforeAll(() => {
        jest.spyOn(global, 'fetch')
            .mockImplementation(() => Promise.resolve({
                json: () => Promise.resolve({
                    defaultValue: 'test-default-value'
        });    afterEach(() => {
    });    afterAll(() => {

Note: It is good practice to restore any mocks within a describe block after all the tests are run so as to not affect any other tests using the function

Now that we have the setup ready, we can write our tests. We need to test for two things:
1. When the hook is first called, the API call is made and the state received after update has the value from the API call.
2. When we call the setValue function with an updated value, the received state must change to reflect the updated value.

react-test-renderer provides a function, renderHook that behaves as a component which uses the hook passed to it. It returns two things, the result — containing what we return from the hook, and a function waitForNextUpdate which we can await on to check the state after an update.

Also, it is recommended that any asynchronous actions that trigger an update in the state should bee wrapped in an act method.

// useInput.test.jsdescribe('the useInput hook', () => {
    beforeAll(() => {
        jest.spyOn(global, 'fetch')
            .mockImplementation(() => Promise.resolve({
                json: () => Promise.resolve({
                    defaultValue: 'test-default-value'
        });afterEach(() => {
    });afterAll(() => {
    });    it('should make the api call to fetch the default value and set it in the state', async () => {
      const {
      } = renderHook(() => useInput());
      await waitForNextUpdate();
  });    it('should update the state when the setValue function is called', async () => {
      const {
      } = renderHook(() => useInput());
      await waitForNextUpdate();
      act(() => {

And that’s how we test custom hooks in react! You can find the code for the entire tutorial on github at the link below: GitHub

Hope this makes things clear; Please drop any comment/doubts/suggestions for further blog post topics as a response below 👇

Cheers ☕️

#reactjs #javascript #web-development

What is GEEK

Buddha Community

The React Custom Hooks Guide - Tutorials and Examples
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