Hooks 🎣

Hooks are functions that give you React features like state and lifecycle methods without classes

  1. Hooks make it easier to reuse stateful logic.

  2. Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.

  3. Hooks are functions that let you β€œhook into” React state and lifecycle features from function components.

  4. Hooks don’t work inside classes β€” they let you use React without classes.

  5. Basically you can hook them whenever you want so you don't want to follow the conventional lifecycles. You can hook and unhook your code in your function. The code is cleaner this way.

  6. Each call to a Hook has a completely isolated state β€” so you can even use the same custom Hook twice in one component.

State Hook useState

  • Call it inside a function component to add some local state to it

  • useState returns a pair: the current state value and a function that lets you update it.

Context Hook useContext

  • Accepts a context object and returns the current context value for that context

  • useContext lets you subscribe to React context without introducing nesting

Reducer Hook useReducer

  • useReducer lets you manage local state of complex components with a reducer

Effect Hook useEffect

  • It adds the ability to perform side effects from a function component

  • Mainly used for data fetching, subscriptions, or manually changing the DOM from React components

  • They are side effects because they can affect other components and can’t be done during rendering.

  • It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

  • Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.

Last updated