0% found this document useful (0 votes)
6 views

62adc137946db2dbb8e23d30 - React Hooks

The document discusses React hooks like useState, useEffect, useReducer and useCallback. useState is used to manage state in functional components. useEffect is used to handle side effects like data fetching. useReducer provides an alternative to useState for managing complex state logic in a reducer function. useCallback memoizes functions to optimize re-renders.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

62adc137946db2dbb8e23d30 - React Hooks

The document discusses React hooks like useState, useEffect, useReducer and useCallback. useState is used to manage state in functional components. useEffect is used to handle side effects like data fetching. useReducer provides an alternative to useState for managing complex state logic in a reducer function. useCallback memoizes functions to optimize re-renders.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

useState is used to implement states in functional

useState compoenents.

useState returns an array with two elements


Declaring state
first one is state value

React Hooks
const [name, setName] = useState(“name”)
second is function to update the state value

Using & Updating state


CHEAT SHEET 01 <div>

Hey ${name}, Welcome!

<div>
updating the state, with a button click
<button onClick={() =>

setName(newValue)}>

New name

</button>

</div>

</div>

useEffect useEffect is used to implement side effects in your react

components. The terms side effects can be your API call or

some logical computations.


Declaring useEffect

React Hooks - Overview useEffect(()=> {

//your logic here, eg: API call, or event listners


Recall lifecycle methods from class components, useEffect

hook handles our logic as same as lifecycle methods.

React Hooks are in-built functions that allow React setName(“name from useEffect”); Clean up is really good practice, and useEffect provides an
developers to use state and lifecycle methods inside easy way to perform your clean up logic. Just return your
},[ ]);
functional components. clean up logic as a function from useEffect and react will

Improved code reusablity. Clean up in useEffect take care of it.

useEffect( => {
Focus on logic than setup Note: When ever useEffect is invoked, it executes the

// your logic here, eg: API call, or event listners return/clean up statement first then your side effect logic.
Custom hooks to reuse logic
setName(“name from useEffect”);
empty array -> [ ]
// return a clean up function This means that the useEffect does’nt have any

return () => setName(“”); dependency it will executed only once when your

component mounts.
},[ ]);
using useReducer hook

React Hooks
The useReducer hook accepts 3
const Counter = ({initialCount}) = >
arguements
// calling useReducer hook to get access to the state tree

const [state, dispatch] = useReduce(reducer, initialCount, init); reducer: our state tree initialCount: initial

CHEAT SHEET 02 return ( state value, if any init: function to reset the
state tree.
<>

Count: {state.count}
useReducer hook returns the state
With dependency in useEffect The dependency list can be passed as an {/* calling dispatch function returned from the useReducer
tree and dispatch function, state tree is
array as the second arguement. hook to dispatch actions. */} used to access the values and dispatch
useEffect( => {
<button function is used to dispatch changes.
//your logic here, eg: API call or event listners onClick={() => dispatch({type: reset, payload: initialCount})}>
dependency array ->[dependencylist]

setName(“name from useEffect”); This means that the useEffect will execute Reset

only when there is a change in the </button>


// return a clean up fucntion
dependecies provided. <button onClick={() => dispatch({type: decrement })}>
return () => setName(“”); <button onClick={() => dispatch({type: increment })}>+

</>
} [ name ]);
);

useReducer
Creating a reducer/state
// init function to reset state object useCallback
function init(initalCount) { You can pass a function to useCallback
return {count: initialCount}; Declaring useCallback and it will return the memoized version of
it and you can us the memoized function
} useReducer in react is an alternative to
const handleClick = useCallback(() => { in your components.
// reducer function that decoupled and grouped our state useState, It is an efficient placeholder to
function reducer(state, action){ // handle the click event
store our state. Also, it provides you more
useCallback in react is used to remember a
switch (action.type){ control to manage the state. // assuming this function has some event listner something, it might be a function or some
case ‘increment’:
variable. useCallback will return a memoized
}, []);
return{count: state.count + 1}; The reducer is nothing but our complex version of that.
case ‘decrement’: state divided based on certain condition.
return{count: state.count - 1}; Using function in JSX Case study
It really usefull because whenever our
case ‘reset’:
return onClick={handleClick}> component re-renders it creates those
return init(action.payload);
functions and variable again, this practice
default: Click Me! is not tolerable if we are assigning event
throw new Error(); </button> listeners, useCallback will make sure that it

} does’nt re-render along with the component.

}
React Hooks
CHEAT SHEET 03

useRef
Declaring useRef useRef in react is used to directly access the DOM and perform
updates or any other operation. And similar to useCallback it
const element = useRef(null); // null or initial value returns the same states regardless of re-renders.

Using useRef in functions to access DOM directly


.current property refers to current element.
const handleRef = () => {
element.current.value; // get or add value for the element .value: will hold the current value of the refered element.

element.current.focus(); // focus the element


.focus: is used to focus the element.
};

linking the element to useRef object


<textarea ref={element} rows="5" cols="33" />

To refer an element, just pass the object that was


returned from useRef to an element’s ref attribute.
And react will provide access for that.

You might also like