DEV Community

Cover image for React-Hooks basics
Shivam
Shivam

Posted on • Edited on

React-Hooks basics

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class.

When to use a Hooks:
If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.

Rules to use Hooks:

  1. Only call Hooks from React functions,
  2. Only Call Hooks at the Top Level.
  3. Hooks can call other Hooks

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Don’t call Hooks from regular JavaScript functions. Instead, you can:

  • Call Hooks from React function components.
  • Call Hooks from custom Hooks.

*Hooks States with: *
Hook state is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state.

Hooks Effect:
The Effect Hook allows us to perform side effects in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

Built-in Hooks:
Here, we describe the APIs for the built-in Hooks in React. The built-in Hooks can be divided into two parts, which are given below:

Basic Hooks

  • useState
  • useEffect
  • useContext

Additional Hooks

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

eg:

useState eg:

import React, {
useState
} from 'react';

function Demo1() {
const [count, setCount] = useState(0);
return (


Count: {count}




);
}
export default Demo1;

useEffect eg:

function Demo2() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = You clicked ${count} times;
});

return (


You clicked {count} times




);
}

useContext eg:

const TestContext = React.createContext();

function Display() {
const value = useContext(TestContext);
return

{value}, I am learning react hooks.;
}

function App() {
return (



);
}

useRef eg:

function App() {
let [name, setName] = useState("Nate");

let nameRef = useRef();

const submitButton = () => {
setName(nameRef.current.value);
};

return (


{name}

  <div>
    <input ref={nameRef} type="text" />
    <button type="button" onClick={submitButton}>
      Submit
    </button>
  </div>
</div>

);
}

More advanced hooks:
The 3 hooks mentioned above are considered to be the basic hooks. It’s possible to write entire applications using only useState, useEffect, and useContext, you could get away with just the first two. The hooks that follow offer optimizations and increasingly niche utility that you may never encounter in your applications.
useCallback:
React has a number of optimizations that rely on props remaining the same across renders. One of the simplest ways to break this is by defining callback functions inline. That’s not to say that defining functions inline will cause performance problems — in many cases, it has no impact. However, as you begin to optimize and identify what’s causing frequent re-renders, you may find inline function definitions to be the cause of many of your unnecessary prop change.
import doSomething from "./doSomething";
const FrequentlyRerenders = ({ id }) => {
return (
onEvent={useCallback(() => doSomething(id), [id])}
/>
);
};
useMemo:
It's closely related to useCallback, but for optimizing data processing. It has the same API for defining what values it depends on as useEffect and useCallback.
const ExpensiveComputation = ({
data,sortComparator, filterPredicate}) => {
const transformedData = useMemo(() => {
return data
.filter(filterPredicate)
.sort(sortComparator);
},[data, sortComparator, filterPredicate]);
return

;
};
useRef:
useRef provides a mechanism for these cases. It creates an object that exists for as long as the component is mounted, exposing the value assigned as a .current property.
// DOM node ref example
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// current points to the mounted text input element
inputEl.current.focus();
};
return (
<>


</>
);
}// An arbitrary instance property
  function Timer() {
           const intervalRef = useRef();
           useEffect(() => {
              const id = setInterval(() => {
                // ...
              });
           intervalRef.current = id;
           return () => {
              clearInterval(intervalRef.current);
           };
         });
  }

useReducer:
This hook has interesting implications for the ecosystem. The reducer/action pattern is one of the most powerful benefits of Redux. It encourages modeling UI as a state machine, with clearly defined states and transitions. One of the challenges to using Redux, however, is gluing it all together. Action creators, which components to connect(), mapStateToProps, using selectors, coordinating asynchronous behavior.

Rarely used hooks:

_useLayoutEffect:_If I use any of these 3, I anticipate it will be useLayoutEffect. This is the hook recommended when you need to read computed styles after the DOM has been mutated, but before the browser has painted the new layout. This gives you an opportunity to apply animations with the least chance of visual artifacts or browser rendering performance problems. This is the method currently used by react-flip-move

_useMutationEffect:_This is the hook I’m having the hardest time wrapping my head around. It’s run immediately before React mutates the DOM with the results from render, but useLayoutEffect is the better choice when you have to read computed styles. The docs specify that it runs before sibling components are updated and that it should be used to perform custom DOM mutations. This is the only hook that I can't picture a use case for, but it might be useful for cases like when you want a different tool (like D3, or perhaps a canvas or WebGL renderer)

React Hooks Tutorial for Beginners: setting up the project
npx create-react-app exploring-hooks
(You should have one of the latest version of Node.js for running npx).

In React component, there are two types of side effects:
1.Effects Without Cleanup
2.Effects With Cleanup

Advantage of React.js :

  1. Easy to Learn and Use
  2. Creating Dynamic Web Applications Becomes Easier
  3. Reusable Components
  4. Performance Enhancement
  5. The Support of Handy Tools
  6. Known to be SEO Friendly
  7. The Benefit of Having JavaScript Library
  8. Scope for Testing the Codes

Disadvantage of React.js

  1. The high pace of development
  2. Poor Documentation
  3. View Part
  4. JSX as a barrier

In conclusion
Hooks have me excited about the future of React all over again. I’ve been using this tool since 2014, and it has continually introduced new changes that convince me that it’s the future of web development. These hooks are no different, and yet again substantially raise the bar for developer experience, enabling me to write durable code, and improve my productivity by extracting reused functionality.
I expect that React applications will set a new bar for end-user experience and code stability.

Questions:
Q. Which versions of React include Hooks?
Starting with 16.8.0, React includes a stable implementation of React Hooks for:
* React DOM
* React Native
* React DOM Server
* React Test Renderer
* React Shallow Renderer

Q. Do I need to rewrite all my class components?
No. There are no plans to remove classes from React.

Q. What can I do with Hooks that I couldn't with classes?
Hooks offer a powerful and expressive new way to reuse functionality between components.

Q. How much of my React knowledge stays relevant?
Hooks are a more direct way to use the React features you already know — such as state, lifecycle, context, and refs. They don't fundamentally change how React works, and your knowledge of components, props, and top-down data flow is just as relevant.

Q. How to test components that use Hooks?
From React point of view, a component using Hooks is just a regular component. If your testing solution doesn't rely on React internals, testing components with Hooks shouldn't be different from how you normally test components.

------Thanks for the read.---------

Top comments (1)

Collapse
 
irandeeprana profile image
Randeep Rana

One of the best blog i ever read. Thanks for sharing sir