Introduction To Basic Hooks

Hooks are the new feature introduced in the React 16.8 version. Hooks permits to use state and other React features without writing a class. Hooks works as functions, “hook into” React state and lifecycle features from function components. Also, it does not replace your knowledge of React concepts.
Hooks have been announced at React Conf 2018.

Hooks provide a powerful way to combine state, props, components, refs, lifecycle.

Here is a list of hooks available. Apart from that there is always an option of re-using these and creating your own custom hooks to reuse stateful behavior between different components.

Yes, you heard that right! Doesn’t that sound cool?

  • useState
  • useEffect
  • useContext
  • useRef
  • useMemo and useCallback
  • useReducer etc…

In this article we will just cover the basics hooks in detail.

1. useState: New hook takes an object where we define the initial values and validate function, The function also returns an object. We are creating the values.Values and setValues will store and set the value of the form fields.
The component can modify its state.To enable state management for functional components we need useState() hook.
Initializing state, Reading state, Updating state with one single function call.
useState contains a pair: current state value and a function to update it. Just like below. It is similar as using this.setState in the traditional method.

import {useState} from 'react';
import { Text, TouchableOpacity } from 'react-native';

function Example() {

 // Declare a state variable, let’s call it "count" 

const [count, setCount] = useState('0');

  return (

    <>

      <Text>You clicked {count} times</p>

      <TouchableOpacity onPress={() => setCount(count + 1)}>

        Click me

      </TouchableOpacity>

    </>

  );

}

2. useEffect: useEffect is here for fetching data, changing things, Adding event listeners also.useEffect can be used to set up and shut down correctly as part of a component’s lifecycle.
3 most commonly used lifecycle methods are componentDidMount, componentDidUpdate and componentWillUnmount.
You might be wondering 🤔 how this single hook can serve the purpose of different lifecycle methods! The answer to this is yes that can happen. Let’s take an example of a BackHandler for the same.

import { BackHandler } from 'react-native';
function Example() {
useEffect(() => {

// This serves as componentDidMount
BackHandler.addEventListener('backPress', handleBackButton);
});
// This serves as componentWillUnmount
return () => {
BackHandler.removeEventListener('backPress');
};
}, []);

const handleBackButton = () => {
BackHandler.exitApp();
};

In the above example, the BackHandler listener will be removed when the component unmounts, as well as before re-running the effect due to a subsequent render.

3. useContext: useContext allows us to access context properties from anywhere within our components. If any prop needs to be passed through several components down the tree, useContext can be used. Let’s take an example where we have 3 components A->B->C in a hierarchy and we need to use a theme in Component C that has been provided in Component A, the prop need not be passed unnecessarily to Component B and can be directly consumed by Component C which is possible with useContext. useContext can be used like:

const value = useContext(MyContext);

Let’s take an example for the store:

const colors = {
blue: "#03619c",
yellow: "#8c8f03",
red: "#9c0312"
};

export const ColorContext = React.createContext(colors.blue);

Provide Context

Then, we can provide our context to whatever child component needs it. In this example, we create colors for the whole app, so we will wrap it in our App:

import { ColorContext } from "./ColorContext";

function App() {
return (

);
}

Consume Context

We can use which is available in both class-based and functional components. It would look something like this to use

return (
  
    {colors => ...}
  
);

Yet, consuming our context in this manner is only available in the return block so can’t be accessed outside. To access it outside the JSX tag it can be out as

static contextType = ColorContext;

This works for class-based components but for functional components the same can be implemented with useContext as:

import React, { useContext } from "react"
   const MyComponent = () => {
const colors = useContext(ColorContext);
 
  return ...;
};

4. useRefs: These are probably used to access a DOM component directly or update the same. Here is an example of a DOM component ScrollView using useRef.

const scrollRef = React.createRef();
return (

   
...

);
 
// Can be used anywhere within the component outside render
scroll.current.scrollTo({x: 0, y: 0, animated: true});

There are many hooks apart from these which we can cover in further articles. Apart from this using these hooks custom hooks can also be created.

At last I will only say as always, hope this article helps you in understanding the basic hooks concept like other articles of mine.


Keep Spreading Knowledge and Happy Coding!! 🙂🙂

Shivangi

Tech Expert

Shivangi is a React Native developer with over 3.5+ work of experience with good knowledge in Android, React Native applications. She is proficient in requirement analysis, application development, and maintenance, functional studies. She is dedicated to continuously developing, implementing, and adopting new technologies to maximize development efficiency and produce innovative applications. she is a self-motivated, quick learner and she loves to resolve technical issues.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks