Hooks
Hooks
➢ States
➢ Hooks vs States
➢ Types of Hooks
Hooks
Hooks States
Hooks are exclusive to functional States, as a concept, apply to both class and
Functional vs. components, allowing them to handle state functional components, but in different
Class Components and other React features. ways.
With hooks, state management shifted to state was managed in class components with
State Management functional components via useState. this.state and setState
• State Hooks
• Context Hooks
• Ref Hooks
• Effect Hooks
State Hooks
• State Hooks stores and provide access to the information. To add state in
Components we use:
• useState Hook: useState Hooks provides state variable with direct
update access.
Syntax:
const [state, setState] = React.useState(initialState);
• state: The current state value.
• setState: A function used to update the state. Calling this function with
a new value triggers a re-render.
• initialState: The initial value for the state. It can be any type, including
primitive values (like strings, numbers, booleans), arrays, objects, etc.
Ex: UseState Hooks
State Hooks
• useReducer Hook: useReducer Hook provides a state variable along
with the update logic in reducer function.
• It's particularly useful when state transitions involve multiple steps or
when you need to handle different types of actions to update state.
Syntax:
const [state, dispatch] = React.useReducer(reducer, initialState);
• Refs creates the variable containing the information not used for
rendering e.g. DOM nodes.
• useRef Hook:The useRef is a hook that allows to directly create a
reference to the DOM element in the functional component.
Syntax:
const refContainer = useRef(initialValue);
React Ref Hooks
Effect Hooks
• Effects connect the components and make it sync with the system. It
includes changes in browser DOM, networks and other libraries.
• useEffect Hook:useEffect Hook connects the components to external
system
• The useEffect in ReactJS is used to handle the side effects such as
fetching data and updating DOM.
• Syntax:
useEffect(<FUNCTION>, <DEPENDECY>)