Skip to content
Related Articles

Related Articles

Improve Article

Things You Should Know About React Hooks

  • Difficulty Level : Medium
  • Last Updated : 18 Jul, 2021

React…We all know the importance of this library in the tech industry. Most of the applications are switching to React because of its advantages and features. There are many features of React. React hooks is one of them. React hooks was first released in October 2018. In React a lot of developers use the lifecycle method which is nothing, but just a series of components. It is used from the birth of React component to its death. 

Things-You-Should-Know-About-React-Hooks

render(), componentDidMount(), componentDidUpdate() componentWillUnmount() all these are the lifecycle method. React hooks is the alternative approach of state management and lifecycle method. There are many hooks used for different purposes. Some of them are useReducer, useState, useCallBack, useMemo, useRef, useDispatcher etc. 

In this blog, we will discuss the common hooks, the benefits of React hooks, the rules of React hooks along some examples.

Benefits of Using React Hooks

Hooks provide a lot of benefits to the developers. It makes your component better, and it helps in writing clear, concise, and maintainable code. It just cut all the unnecessary code from your component and makes your code more readable. But the question is when to use React hooks?



Use Hooks when you’re writing a function component, and you want to add some state to it. Earlier this job was done by using a Class, but now you can write the hooks inside a function component. 

Rules of Hook

Below are the main rules of using React hooks…

1. Always call hooks at the top level. Do not call it inside loops, conditions, or nested functions. You will be ensured that hooks can be called in the same order each time component renders. 

2. Hooks can not be called from regular JavaScript functions. You can call it from React function components. One hook can call another hook. 

Hooks Effect

Hooks effect allows you to perform a side effect in function components. Hooks effect has no use of function components available in-class components. Hooks effects are similar to the lifecycle method componentDidMount(), componentDidUpdate(), and componentWillUnmount(). 

Hooks effect has the common features given below…

  • Updating the DOM
  • Fetching and Consuming data from server API
  • Setting up subscription

Below is one of the examples of React hooks.

Javascript






import React, { useState, useEffect } from 'react';  
    
function CounterExample() {  
  // Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);  
  const incerementCount = () =>setCount(count+1);
    
  useEffect(() => {  
    // Update the document title using the browser API  
    document.title = `You clicked ${count} times`;  
  });
    
  return (  
    <div>  
        
  
<p>You clicked {count} times</p>
  
    
      <button onClick={incrementCount}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CounterExample;

 
 

Context Hook

 

There is a concept of Context hook in React. Context hook is used in Context API. You create the context in React and this hook is used to interact with created context. An example is given below…

 

Javascript




import React, { useContext } from 'react';
const ExampleContext = React.createContext();
function Display() {
   const Examplevalue = useContext(ExampleContext);
   return <div>{Examplevalue}, This value is from context.</div>;
}
function App() {
   return (
      <ExampleContext.Provider value={"Tamil"}>
         <Display />
      </ExampleContext.Provider>
   );
}

 
 

Reducer Hook

 

You might have listened to this word if you have worked with Redux. Reducer hook works as an alternative for a state hook. When a state is changed it gets bundled in a central function called Reducer. After that state will be updated depending on the action and existing state. One of the examples is given below… You can rewrite the state hook example as given below…

 

Javascript






import React, { useReducer } from 'react';
const initialState = {count: 0};
  
function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'decrement': return { count: state.count - 1 };
    default: throw new Error();
  }
}
  
function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      <h2>Count: {state.count}</h2>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

 
 

Ref Hook

 

Reference hook refers to the React element created by the render method. An example is given below…

 

Javascript




import React, { useRef } from 'react';
function App() {
  const newElement = useRef(null);
  const onButtonClick = () => {
    newElement.current.focus();
  };
  return (
    <>
      <input ref={newElement} type="text" />
      <button onClick={onButtonClick}>Focus to Element</button>
    </>
  );
}

 
 

Final Thought

We have discussed the major hooks and their usage with code examples. These hooks are not limited here. Once you will have experience in React, you will be using many more hooks such as useDispatch, useSelect, etc. Each one of them has its own application.

 

Go Premium (An Ad Free Experience with many more features)




My Personal Notes arrow_drop_up
Recommended Articles
Page :