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!! 🙂🙂

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?