Hooks || how to use of hooks in react.js
Tags: webdev, javascript, programming, react
Published: 2024-03-17 06:44:52


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ldxnogej17caf08ba00a.png)React 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzt05xdep330chmrbwk1.png)  

## code:
```js

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>
       );
}




```

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/viyxd48ngnbvh4aanqxd.png)
## code:

```js
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>

	);
}
```
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcrsfvu0b1gerr0wqcm5.png)

```js
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>;
 }
```
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av52awzjizner3ob2m5q.png)
## code:
```js
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>
  );
};

```
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtav9kv16aul9sws5jks.png)

```js
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>
  );
}


```
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](https://github.com/04anilr)
[website](https://my-portfolio-two-lemon-36.vercel.app/)


[Array methods in react.js ](https://dev.to/04anilr/how-to-use-array-methods-in-real-project-example-add-new-record-3o82)
[Fragment in react.js](https://dev.to/04anilr/fragment-in-reactjs-example-of-fragment-299a) 
[Conditional rendering in react.js](https://dev.to/04anilr/conditional-rendering-in-react-conditional-rendering-example-in-react-3j46)
[Children component in react.js](https://dev.to/04anilr/methods-of-react-children-component-in-react-4ol7)
[use of Async/Await in react.js](https://dev.to/04anilr/how-to-use-asyncawait-3a3o)
[Array methods in react.js](https://dev.to/04anilr/array-methods-in-reactjs-36jb)
[JSX in react.js](https://dev.to/04anilr/jsx-in-reactjs-3f7o)
[Event Handling in react.js](https://dev.to/04anilr/event-handling-in-react-5hc7)
[Arrow function in react.js](https://dev.to/04anilr/arrow-functions-in-react-4gb2)
[Virtual DOM in react.js](https://dev.to/04anilr/how-to-work-virtual-dom-in-react-dom-1b39)
[React map() in react.js](https://dev.to/04anilr/how-to-create-react-map-24pp)
[How to create dark mode in react.js](https://dev.to/04anilr/how-to-create-dark-mode-in-react-js-2kn2)
[How to use of Props in react.js](https://dev.to/04anilr/props-and-state-with-example-1bl1)
[Class component and Functional component](https://dev.to/04anilr/class-component-functional-component-in-react-k43)
[How to use of Router in react.js](https://dev.to/04anilr/how-to-use-of-router-in-reactreact-router-1163)
[All React hooks explain ](https://dev.to/04anilr/react-hooks-cheat-sheet-2hic)
[CSS box model ](https://dev.to/04anilr/css-box-model-work-2k0a)
[How to make portfolio nav-bar in react.js](https://dev.to/04anilr/how-to-make-nav-bar-for-portfolio-website-365m)