Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use React Hooks

Tags:

reactjs

redux

I was trying to comprehend the importance of Hooks

From React docs, it says

They let you use state and other React features without writing a class.

Wasn't the whole idea behind the functional component was that it is going to be stateless so that it doesn't cause re-render of react app? Like, if you were to use react hooks, where and why would you use it?

You can always create a state by yourself which won't cause re-render of functional component const state = {}

My Question is:

  1. What is the advantage of state in functional component
  2. When would use react-hooks instead of actual state-based component in react
like image 446
anny123 Avatar asked Dec 02 '22 10:12

anny123


2 Answers

I'll try to be concise. React Hooks ware introduced in the React 16.8.. Hooks make it possible to organize logic in components, making them tiny and reusable without writing a class. In a sense, they’re React’s way of leaning into functions because, before them, we’d have to write them in a component and, while components have proven to be powerful and functional in and of themselves, they have to render something on the front end. That’s all fine and dandy to some extent, but the result is a DOM that is littered with divs that make it gnarly to dig through through DevTools and debug.

Well, React Hooks change that. Instead of relying on the top-down flow of components or abstracting components in various ways, like higher-order components (HOC), we can call and manage flow inside of a component.

Hooks apply the React philosophy (explicit data flow and composition) inside a component, rather than just between the components. Unlike patterns like render props or higher-order components, Hooks don’t introduce unnecessary nesting into your component tree.

Additionally, React Hooks can help you with:


- No need to learn, memorize, implement lifecycle methods:

This - componentDidMount

class Example extends React.Component {
  componentDidMount() {
    console.log('I am mounted!');
  }
  render() {
    return null;
  }
}

Turns into:

useEffect hook

function Example() {
  useEffect(() => console.log('mounted'), []);
  return null;
}

This - componentDidUpdate

componentDidMount() {
  console.log('mounted or updated');
}

componentDidUpdate() {
  console.log('mounted or updated');
}

Turns into:

useEffect(() => console.log('mounted or updated'));

componentWillUnmount

componentWillUnmount() {
  console.log('will unmount');
}

Turns into:

useEffect(() => {
  return () => {
    console.log('will unmount');
  }
}, []);

... just to name a few


- Complex components become hard to understand:

We’ve often had to maintain components that started out simple but grew into an unmanageable mess of stateful logic and side effects. Each lifecycle method often contains a mix of unrelated logic and in many cases it’s not possible to break these components into smaller ones because the stateful logic is all over the place. It’s also difficult to test them. Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods. You may also opt into managing the component’s local state with a reducer to make it more predictable.
May I suggest looking into useEffect hook.

- Composable, Reusable Logic:

It’s hard to reuse stateful logic between components. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community. Essentially, we can build our own custom Hooks


We’ve merely scratched the surface of what React hooks are capable of doing, but hopefully, this gives you a solid foundation. Here are a few more pre-defined hooks:

  • userReducer() An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method.

  • useMemo() Returns a memoized value. Pass a “create" function and an array of inputs. useMemo will only recompute the memoized value when one of the inputs has changed.

  • useRef() 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.

  • useContext() Now you can make use of Context API in functional components using useContext(). This saves you from the hassle of prop drilling.


Here are a few diagrams to [hopefully] drive the point home


React Hooks in essence

enter image description here


React Hooks - under the hood:

enter image description here


React Hooks lifecycle:

enter image description here

Class-based components lifecycle:

enter image description here


I hope you're a little bit hooked now :)

like image 102
Dzenis H. Avatar answered Feb 06 '23 20:02

Dzenis H.


Assume you have a functional component that depends on data from an api call. You want to show loading spinner when data isn't there, and display data when data is fetched.

Before hooks, we were forced to change the supposed functional component to class component to make the api call and to manage state. Now, all that your have to do is use hooks.

Quoting react documentation:

A Hook is a special function that lets you “hook into” React features.

Hooks are really helpful in breaking down business logic. In class components, we tend to put in all business logic in lifecycle methods, with the invent of hooks, the lines of code reduces drastically and is more developer friendly as well. Also, minifiers/uglifiers have a hard time working with Classes. We totally eliminate the overheads with hooks.

like image 43
Avanthika Avatar answered Feb 06 '23 21:02

Avanthika