Monday, September 1, 2025

React Hooks

Hooks

·     Hooks came in react version 16.8

·     React Hooks are functions that allow functional components in React to manage             state, handle side effects, and access other React features without needing class components.

·     Hooks allow you to use state (useState) and handle side effects (useEffect) in functional components.

·     React hooks allows you to use react features without having to write a class. e.g. State of a component.

·     Hooks won't work inside classes.

Why we need hooks?

·     We need to understand 'this' keyword in class components so to avoid it's confusion we can eliminate it by using hooks.

·     We need to remember to bind event handlers in class components so we can avoid it here.

·     Classes make hot reloading unreliable.

·     We are handling stateful component logic in Classes – so better way is there in Hooks

·     In class components we create complex components for complex scenarios like data fetching / subscribing to events, where related code is scattered, like data fetching in componentDidMount and componentDidUpdate, so cannot break components into smaller ones.

·     Hooks let us organize the logic inside a component into reusable isolated units.

·     Replaces need for class components.

Advantages of Hooks

·     Simplifies state management and lifecycle methods in functional components.

·     Provides reusable logic with custom hooks.

·     It reduces unnecessary re-renders through memorization.

·     It provides easy migration of existing class components.

Note -

·     Only call hooks at the top level.

·     Don't call inside loops, conditions, or nested functions

·     Only call hooks from react functions and not from any regular JS functions.


Javascript

  Let and const scope of let b in outside and inside of block value of a and b before initialization Multiple blocks Closures var and let in...