DEV Community

Cover image for Hooks || how to use of hooks in react.js
Anil
Anil

Posted on • Updated on

Hooks || how to use of hooks in react.js

Image descriptionReact Hooks are build-in functions that allow you to use state and React features, like lifecycle methods and context, in functional components without needing to write a class component.

Image description

code:


import React, (useState) from 'react';

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

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




Enter fullscreen mode Exit fullscreen mode

2. useEffect

This hook lets you perform side effects in functional components. it is a close replacements for componentDidMount, componentDidupdate, and componentwillunmount in class components

Image description

code:

import React, { useState, useEffect } from "react";

function counter() {
    const [count, setCount] = useState(0);
    useEffect(() => {
        documc.title = 'you clicked ${count} time ';
        return () => {
            Document.title ='react App';
        };



    },[count]);
    return (
        <div>
            <p>You clicked {count} times</p>
                        <button onClick={() => setCount(coun 
                        + 1)}>click me </button>
            </div>

    );
}
Enter fullscreen mode Exit fullscreen mode

3. useContext

This Hook lets you subscribe to React context without introducing nesting. it accepts a context object and returns the current context value for that context.

Image description

import React,{useContext} from 'react';
const ThemeContext = React.createContext('light');


 function Themebutton() {
     const Theme = useContext(ThemeContext);

  return<button theme={theme}> i am style by theme 
         context</button>;
 }
Enter fullscreen mode Exit fullscreen mode

4. useReducer

An alternative to useState. Accepts a reducer of type (sate, action) => newState and returns the current State paired with a dispatch method.
Example:

it is particularly useful when the state logic is complex and involves multiple sub-value, or when the next state depends on the previous one. useReducer is an alternative to useState.

while useState is great for handling independent pieces of state useReducer excels at handling more complex, interconnected state that involves multiple changes in an atomic and predicable manner.

Image description

code:

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 Counter  () {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment'
       })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' 
       })}>Decrement</button>
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

5. useRef

This Hook creates a mutable ref object whose current property in initialized to the passed argument. it is handy for keeping any mutable value around similar to how you did use instance fields in class.

Image description

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);
  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

React hooks provide a concise way to manage state, effects, context, and more in functional components:

  1. useState: Manages component state.
  2. useEffect: Handles side effects.
  3. useContext: Accesses context in components.
  4. useReducer: Alternative state management.
  5. useRef: Creates mutable references.

Using these hooks leads to cleaner, more efficient code in React applications.

github
website

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (1)

Collapse
 
lehungtin11 profile image
Hung Tin Le

Thanks for sharing