React-Hooks basics
Tags: frontend, javascript, react, frameworks
Published: 2020-10-30 14:54:04

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 (
    <div>
      Count: {count}
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
}
export default Demo1;

_useEffect eg:_

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

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

_useContext eg:_

const TestContext = React.createContext();

function Display() {
  const value = useContext(TestContext);
  return <div>{value}, I am learning react hooks.</div>;
}

function App() {
  return (
    <TestContext.Provider value={"Kaleem"}>
      <Display />
    </TestContext.Provider>
  );
}

_useRef eg:_

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

  let nameRef = useRef();

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

  return (
    <div className="App">
      <p>{name}</p>

      <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 (
              <ExpensiveComponent
                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 <Table data={transformedData} />;
       };
_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 (
                <>
                  <input ref={inputEl} type="text" />
                  <button onClick={onButtonClick}>
                      Focus the input
                  </button>
                </>
              );
      }// 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.---------_