Overview of ReactJS Hooks
React is a popular JavaScript library developed by Facebook for building user interfaces, especially single-page applications. It allows developers to create large web applications that can update and render efficiently in response to data changes. React is component-based, meaning the UI is built from encapsulated components that manage their own state and can be reused and composed to form complex UIs. Get a concise overview of ReactJS Hooks. Learn how to use them to manage state, side effects, and more in your functional components efficiently.
Core Concepts of React
- Components: The building blocks of a React application. Components can be either class-based or function-based and are responsible for rendering UI elements.
- JSX: JavaScript XML, a syntax extension that looks like HTML but is used in JavaScript to describe the UI structure.
- State: An object that determines how that component renders and behaves. When the state of a component changes, the component re-renders.
- Props: Short for properties, these are read-only inputs passed to components to make them dynamic.
- Virtual DOM: React maintains a virtual representation of the DOM to optimize UI updates.
React Hooks Overview
Hooks are functions that let you “hook into” React state and lifecycle features from function components. They provide a way to use state and other React features without writing a class.
1. useState
- Purpose: Manages state in a functional component.
- Syntax:
jsx
Copy code
const [state, setState] = useState(initialState);
- Example:
jsx
Copy code
import React, { useState } from ‘react’;
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
2. useEffect
- Purpose: Handles side effects in function components (e.g., data fetching, subscriptions).
- Syntax:
jsx
Copy code
useEffect(() => {
// effect code here
return () => {
// cleanup code here
};
}, [dependencies]);
- Example:
jsx
Copy code
import React, { useState, useEffect } from ‘react’;
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
3. useContext
- Purpose: Accesses the value of a React Context, avoiding prop drilling.
- Syntax:
jsx
Copy code
const value = useContext(MyContext);
- Example:
jsx
Copy code
import React, { useContext } from ‘react’;
const MyContext = React.createContext();
function Display() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
function App() {
return (
<MyContext.Provider value=”Hello from context”>
<Display />
</MyContext.Provider>
);
}
For Free Demo classes Call: 8237077325
Registration Link: Click Here!
4. useReducer
- Purpose: Manages more complex state logic, similar to useState but for complex state transitions.
- Syntax:
jsx
Copy code
const [state, dispatch] = useReducer(reducer, initialState);
- Example:
jsx
Copy code
import React, { useReducer } from ‘react’;
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, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: ‘increment’ })}>+</button>
<button onClick={() => dispatch({ type: ‘decrement’ })}>-</button>
</div>
);
}
5. useRef
- Purpose: Accesses and manipulates DOM elements directly or persists values across renders without causing re-renders.
- Syntax:
jsx
Copy code
const refContainer = useRef(initialValue);
- Example:
jsx
Copy code
import React, { useRef } from ‘react’;
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type=”text” />
<button onClick={onButtonClick}>Focus the input</button>
</div>
);
}
6. useMemo
- Purpose: Memoizes a value to avoid costly recalculations on every render.
- Syntax:
jsx
Copy code
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
- Example:
jsx
Copy code
import React, { useMemo, useState } from ‘react’;
function ExpensiveCalculationComponent({ a, b }) {
const result = useMemo(() => {
return expensiveCalculation(a, b);
}, [a, b]);
return <div>{result}</div>;
}
function expensiveCalculation(a, b) {
// Some expensive calculation
return a + b;
}
7. useCallback
- Purpose: Memoizes a function to prevent its recreation on every render, useful for passing callbacks to optimized child components.
- Syntax:
jsx
Copy code
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
- Example:
jsx
Copy code
import React, { useState, useCallback } from ‘react’;
function MyComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return <button onClick={handleClick}>Click me</button>;
}
8. useImperativeHandle
- Purpose: Customizes the instance value exposed to parent components when using ref.
- Syntax:
jsx
Copy code
useImperativeHandle(ref, () => ({
customMethod() {
// logic here
},
}));
- Example:
jsx
Copy code
import React, { useRef, useImperativeHandle, forwardRef } from ‘react’;
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
function App() {
const inputRef = useRef();
return (
<div>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus input</button>
</div>
);
}
9. useLayoutEffect
- Purpose: Similar to useEffect, but it runs synchronously after all DOM mutations. Use this when you need to read layout properties (like dimensions) and re-render synchronously.
- Syntax:
jsx
Copy code
useLayoutEffect(() => {
// effect code here
}, [dependencies]);
- Example:
jsx
Copy code
import React, { useLayoutEffect, useRef } from ‘react’;
function LayoutEffectExample() {
const divRef = useRef();
useLayoutEffect(() => {
console.log(divRef.current.getBoundingClientRect());
}, []);
return <div ref={divRef}>Hello, world!</div>;
}
10. useDebugValue
- Purpose: Displays a label in React DevTools for custom hooks.
- Syntax:
jsx
Copy code
useDebugValue(value);
- Example:
jsx
Copy code
import React, { useState, useDebugValue } from ‘react’;
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
// Assume useEffect is doing something here
useDebugValue(isOnline ? ‘Online’ : ‘Offline’);
return isOnline;
}
Must watch our video on Demand For Full Stack Developers in Future
Author:-
Sonal Vanarse
Call the Trainer and Book your free demo Class for ReactJS Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.