React Hooks Simplified + Cheatsheet

If you using React v16.8 onwards then you must have come across Hooks and these are bunch of functions to manage your application state efficiently. Prior to hooks we were using props (nothing but a parameter value) to pass between components and used State method to save and update those values.

And for more complex application we used Redux for centralizing all props and let components access those from redux store. However, these techniques have some caveats like...

  1. Redux is a huge library and has lot of boilerplate code
  2. state methods can only be available in class components
  3. need to rely on lifecycle methods for some actions eg: do something on page load
  4. class components have increased bundled size when comparing to function components
  5. more code compared to function component with exact same results (for all those one liners...)

So, here is the cheetsheet to use...

want to use state locally ? then useState()
const [getname setname] = useState({first:"foo", last:"bar"})
const firstname = getname.first;
function setval() { setname(x=> {return {...x, first: "awesome foo"}})

want to use lifecycle ? then useEffect()
// empty array runs once and [getname] runs only when getname changes
const [getname setname] = useState({first:"foo", last:"bar"})
useEffect(()=> {console.log}, [getname] or []) 

want to control DOM element ? then useRef()
const el = useRef()
<input ref={el}>

<button onClick ​={()=> el.current.focus()}/>
want to cache and return function results ? then useMemo()
const [getname setname] = useState({first:"foo", last:"bar"})
const val = useMemo(()=> {return functionname ()},  [getname] or []
want to cache the value and return function itself? then useCallback()
const [getname setname] = useState({first:"foo", last:"bar"})
const val = useCallback(()=> {return functionname ()},  [getname] or [])
want to create a universal props accessed to entire app ? then useContext()
App.js
export const themeContext = React.createContext();
<themeContext.Provider value ={darktheme}>App</themeContext.Provider>

Page.js

const dark = useContext(themeContext);
<button style={color:dark}>

want to action, dispatch and reduce ? then useReducer()
const ACTIONS = {ADD_ITEM_TO_CART: "ADD_ITEM_TO_CART"};

function cartReducer(state, action) {
switch(action.type) {
case ACTIONS.ADD_ITEM_TO_CART:
     return {...state, items:[...state.items, action.items]}; 
     default:
     return state;
  }
}

const [state, dispatch] = useReducer(cartReducer, { items: 0 });     
dispatch({type:ACTIONS.ADD_ITEM_TO_CART, payload:{ items:2 } });      

Note: Hooks only works on function component

That's it guys, these are the most used hooks in React and hope these snippets may be helpful. Cheers.

To view or add a comment, sign in

Others also viewed

Explore content categories