Common React Hooks cheatsheet - React, Redux, Router and Ionic friendly
So who is this for?
- Frontend developers writing functional React components
- Ionic React mobile developers
React Hooks
Hooks provide React developers the ability to write functional components while accessing Reacts core features. To put it plainly:
"they let you hook into React state and lifecycle features from functional components".
Cheatsheet
The State Hook - useState()
The useState() hook allows you create, read and update a stateful value for your application. During initial render, the returned state is the initial value passed as seen in the example below.
The setState parameter below is a function declaration that allows updates or mutation to the state. It accepts a new state value and enqueues a re-render of the component
/**
* String value state
*/
const initalState = 'hello world';
const [state, setState] = useState(initialState);
// Update state value
setState('My first update');
The Effect Hook - useEffect()
Operations like data fetching, setting up subscriptions and mutating the DOM are classified as side effects in React. In the React class lifecycle terminology, the useEffect hook is a combination of methods like componentDidMount
, componentDidUpdate
and componentWillUnmount
.
The useEffect hook provides a way of encapsulating "effectful" code. With useEffect, code dependent on the various React lifecycle and state can be triggered based on their dependencies.
useEffect provide an optional cleanup return method which runs before the component is removed from the UI to prevent memory leaks. Example below.
import { useEffect } from 'react';
useEffect(() => {
const timer = setInterval(()=>{
console.log('I am here again');
}, 5000);
return () => {
// Stop the interval timer
clearInterval(timer)
};
});
The above snippet would run on each re-render of the functional component in which they are resident. This maps to the componentDidUpdate
lifecycle method. To ensure, it runs only once i.e componentDidMount
, pass an empty dependency array as a second parameter like below.
import { useEffect } from 'react';
useEffect(() => {
const timer = setInterval(()=>{
console.log('I am here again');
}, 5000);
return () => {
// Stop the interval timer
clearInterval(timer)
};
}, []);
State variables can also be passed into the array to make the useEffect
method run on each mutation of such state variables as seen below.
import { useState, useEffect } from 'react';
const [state, setState] = useState('');
useEffect(() => {
const timer = setInterval(()=>{
console.log('I am here again');
}, 5000);
return () => {
// Stop the interval timer
clearInterval(timer)
};
}, [state]);
TLDR; on UseEffect
useEffect
is deferred until after the browser has painted. To fire before painting, the useLayoutEffect
can be used. It has the same function signature as useEffect
.
The Reference Hook - useRef()
A common use case of this hook is in keeping a reference to a DOM element for future manipulation as seen below.
import { useRef } from 'react';
const FunctionalComponent = () => {
const listRef = useRef(null);
const changeColour = () => {
listRef.current.style.color = '#ab09ab';
};
return (
<div>
<p ref={listRef}>Hello there</p>
<button onClick={changeColour}>Change Colour!</button>
</div>
);
};
useRef
returns a mutable object with a current
property which holds a reference to the passed argument or an HTML element with assigned ref property.
The Redux Dispatch Hook - useDispatch()
If you are familiar with Redux in the React class environment, then you would have used connect
as a wrapper around a React component at some point. The useDispatch
hook gives you a cleaner access route to mutating your redux state. See below.
import { useDispatch } from 'react-redux';
// Redux action import
import setColour from '../actions/setColour'
const FunctionalComponent = () => {
const dispatch = useDispatch();
const changeColour = (col) => {
dispatch(setColour(col));
};
return (
<div>
<button onClick={()=>changeColour('blue')}>Change Colour!</button>
</div>
);
};
The Redux Selector Hook - useSelector()
This is another hook that eliminates the need for the Redux connect
wrapper. The useSelector gives you access to your redux store data. See sample below.
import { useSelector } from 'react-redux';
const FunctionalComponent = () => {
const posts = useSelector(state => state.posts);
return (
<div>
{posts.map(post=>(
<div key={post.id}>
<h4>{post.title}</h4>
<p>{post.body}</p>
</div>
))}
</div>
);
};
We will stop here for now and keep growing the list. Keep an eye out for new hooks ๐
You can also contribute in the comment section!
Get managed hosting and database for your NodeJS, Python, Go applications and more. SQL and NoSQL databases all included under one plan. Start for free today! https://zhap.cloud
Subscribe to my newsletter
Read articles from Chinaza Egbo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Chinaza Egbo
Chinaza Egbo
I seek out simple and scalable solutions to various challenges with tech