3 Hooks Every React Developer Should Know

3 Hooks Every React Developer Should Know

Understand different hooks and know when to use the right ones

Source: Author. Created with [Canva](https://cdn.hashnode.com/res/hashnode/image/upload/v1630753937179/yfllGoTL8.html).Source: Author. Created with Canva.

I recently built a project using a combination of class-based components as well as using the Hooks API and I couldn’t help but notice how the React Hooks was so much easier to use and also didn’t have many of the class-based components downfalls.

React Hooks provides you access to state and lifecycle methods inside a functional component. Thus eliminating the need to refactor a functional component to a class component.

React Hooks are a set of built-in functions( and you can create them too) that enables state-management and side-effects in functional components.

However, knowing when to use which built-in hook and the exact functionality of that function can become confusing at times, especially if you are new to this.

Different React Hooks. [Source](https://cdn.hashnode.com/res/hashnode/image/upload/v1630753938922/eezTBfbQb.html).Different React Hooks. Source.

Below are some of the most important React Hooks that you should know before you start using them:

1. useState

The useState() function is the first hook I learned about and it is the most used & common React hook out there

As the function name suggests, this Hook deals with the state of the component. In other words, it is very similar to this.setState .

You can pass some local state in this hook and it will be preserved whenever the function re-renders.

This hook returns two values: the first is the reactive data and the second is a function that lets you update it.

import React, { useState } from 'react';
function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
// count is the data whereas setCount is an update function

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Here we passed 0 as the argument in the useState() function and it will initialize our constant “count” with the value 0.

React hooks leverage the destructuring feature of JavaScript and if you are unaware of it, do check out my blog discussing some of these modern practices. 5 Modern Practices of JavaScript that Every Developer Should Know 5 best tips and practices for writing clean codemedium.com

You can pass other arguments as well.

const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

2. useEffect

The useEffect() is a versatile Hook that can perform as many as three lifecycle methods.

The componentDidMount, componentDidUpdate, and componentWillUnmount functions are performed by this single hook.

Achieving componentDidMount function using useEffect() is very simple and after understanding this, you will also get how to implement the componentDidUpdate() function.

To make the explanation more clear, we’ll look into how you can do these methods from the useEffect() API by first understanding the arguments it takes.

This hook takes into two arguments — a function and an array.

The first argument specifies the operation that you want to perform every time the component is updated whereas the second argument gives you control over when to update the component.

If you pass an empty array, the useEffect() will only run once when the component is mounted, this performing the componentDidMount method.

function Example() {
  ....
  useEffect(() => {
    document.title = `This runs once`;
  },[]);
}

If you don’t pass the second argument at all, you are essentially running both the componentDidMount as well as the componentDidUpdate method at once.

function Example() {
  ....
  useEffect(() => {
    document.title = `This runs once`;
  });
}

You can make the useEffect() trigger the re-render only when certain data changes by passing that data into the array of the second argument as shown below:

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    
// Update the document title using the browser API    
document.title = `You clicked ${count} times`; 
},
[count]);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

The following useEffect will only trigger re-render when the “count” variable is changed.

Now how to perform the componentDidUnmount using this hook?

To do that, you can return a function from the function that you passed as the first argument in the useEffect() hook. This will become more clear when you see the code:

useEffect(
  () => {
    const subscription = props.source.subscribe();
    return () => {
      subscription.unsubscribe();
    };
  },
  [props.source],
);

Here, you can see that we have returned a function that has a single line of code subscription.unsubscribe(); .

Now, this function will be executed when the component will unmount.

3. useContext

This Hook enables you to implement and use React’s Context API.

In case you don’t know the Context API, it is a system that eliminates the need to pass down props.

In large applications, it may become tiresome to pass props down from the top(parent) component to down(child) components and therefore, Context API can come off as incredibly useful and time-saving.

This Hook allows you to use the Context API and accepts a context object and returns the up-to-date, current context value for that very particular context.

Let’s understand this through an example.

const message={
  passed:'Congrats, you passed the test',
  failed:'You failed this time, try again!'
}
const MessageContext=createContext(message);
function App(){
  return (
    <MessageContext.Provider value={message.passed}>
        <DisplayMessage />
    </MessageContext.Provider>

)
}
function DisplayMessage (){
  const result= useContext(MessageContext);
      return <h1>result</h1>
}

Here we have passed the data from the parent component to the child component using the Context API and the useContext() hook.

Whenever the value changes in the parent provider, the value in the child component will change too.

If you are familiar with the Context API, you must have noticed that we didn’t use the Consumer method and that’s because the useContext() hook is essentially a much better, cleaner replacement of the Consumer method.

But before you go about using this API, remember to only use Context when the data needs to be accessible by many components at different nesting levels as it makes the component hard to reuse.

Conclusion

React Hooks is a relatively new addition to the React framework and it was a much-needed one.

React Hooks essentially lets you “hook into” the state management and lifecycle methods offered by the class-based component and it is a new approach to how we are used to coding in React.

Starting React version 16.8.0, you can use the Hooks API and build complete applications with just it. The best part is that the class components aren’t going anywhere and you are free to stick to the class component as well.

However, it is worth noting that this practice of moving away from class component to functional component might confuse your teammates if they are accustomed to some other language and framework as explained by Razvan Dragomir.

Nonetheless, Hooks provide a way to combine some of the most important React concepts like props, context, state, etc in a very clean, intuitive, and quick way.

Hope you enjoyed reading this article!

Did you find this article valuable?

Support Smart Dev Blogs by becoming a sponsor. Any amount is appreciated!