React-Native Hooks

Fatema Patel 2021-03-31

Objective

Hooks are functions that let us “hook into” React state and lifecycle features from function components.React provides a few built-in Hooks like useState, useEffect, useRef. we can also create our own Hooks to reuse stateful behavior between different components.

What are Hooks?

Hooks were a new addition in React 16.8. They let you use state and other React features without writing a class.

Hooks were introduced in October 2018 as a way to use state and side effects in React function components (see Lifecycle methods in class components). While function components were formerly called functional stateless components (FSCs), they are eventually able to use the state with react hooks and so many people now identify them as function components.

Why Hooks?

Hooks is state management and side-effects in function components and a way of making it more effortless to use only React function components without the need to refactor a React function component to a React class component for using lifecycle methods, in order to use have side-effects, or local state. React Hooks enable us to write React applications with only function components. Thus, there is no need to use class components anymore.

when you use a functional component at that time you realized you need to use state, previously you must change functional component to class component but now you do not need to change it. we directly use hook in our component for access state in the functional component.

Types of Hooks

Basic Hooks

  • useState
  • useEffect
  • useContect

Additional Hooks

  • useRef
  • useReducer
  • useCallback
  • useMemo
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

useState Hook

The useState hook gives you everything you need to manage the state in a function component: initial state, the latest state, and a state update function.


const App = () => {
  // Declare multiple state variables!

  const [age, setAge] = useState(42); //Number
  const [fruit, setFruit] = useState('banana'); //String
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]); // Array
  const [data, setData] = useState({}); // JSON

  useEffect(() => {
    // Similar to this.setState({ fruit: 'orange' })
    setFruit('orange');
  },[]);
  return (
    <>
      <Text>{fruit}</Text>
    </>
  );
};

useEffect Hook

The Effect Hook lets you perform side effects in function components. Similar to componentDidMount and componentDidUpdate methods of the class component.

componentDidMount, componentDidUpdate,  and componentWillUnmount combined in useEffect Hook.

By using useEffect Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. 

userEffect Hook has two arguments one is a functional component to perform when state changes and the second is an array optional argument

we'd need a separate effect to perform the cleanup. But code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together. If your effect returns a function, React will run it when it is time to clean up

In some cases, applying the effect only when components are mount. In class components, we can solve this by writing code inside componentDidMount.Now with useEffect Hook, you just pass an empty array as the second argument of useEffect hooks

In some cases, cleaning up or applying the effect after every render might create a performance problem. In class components, we can solve this by writing an extra comparison with prevProps or prevState inside componentDidUpdate

In some cases, we can tell React to skip applying an effect if certain values haven’t changed between re-renders.

import React, { useEffect } from 'react';

const App = () => {
  useEffect(() => {
    // perform state change
    return () => {
      // cleanUp code
    };
  }, []);
  // [] when you want effect on component mount only
  // [value] effect only when action perform in value state
};

useContext Hook

useContext Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

When the nearest MyContext.Provider above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider. Even if an ancestor uses the shouldComponentUpdate, a rerender will still happen to start at the component itself using useContext.


const App = () => {
  const ThemeContext = React.createContext(themes.light);
  return (
    <ThemeContext.Provider value={themes.dark}>
      <AppStack />
    </ThemeContext.Provider>
  );
}


const ThemedButton = () => {
  const theme = useContext(ThemeContext);
  return (
    <Text style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </Text>
  );
}

useRef Hook

useRef is used to define reference in function component. In class component we have to pass this.ref and in the functional component, we have to pass valueRef.current to access the object.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.


const App = () => {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    <>
      <TextInput ref={inputRef} placeholder="text" />
    </>
  );
};

 

 

 

Summary

Hooks is a state management and side-effects in function components and a way of making it more effortless to use only React function components without the need to refactor a React function component to a React class component for using lifecycle methods, in order to use have side-effects, or local state. React Hooks enable us to write React applications with only function components. Thus, there is no need to use class components anymore.

Created on : 2021-03-30
Written by

Fatema Patel

Jr. React Native Developer

Tags
hook
react-native
react-hook
useState
useEffect
useRef
react
functional component
hooks