Welcome to our comprehensive tutorial on all React hooks! In this tutorial, we will cover everything you need to know about React hooks, including how to use them effectively in your projects.
Before we get started, let’s first understand what React hooks are and why they are important. Hooks are a new addition to React that allows you to use state and other React features without writing a class. This makes your code cleaner, easier to read, and more maintainable.
In this tutorial, we will cover the following React hooks:
- useState
- useEffect
- useContext
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
By the end of this tutorial, you will have a solid understanding of how each of these hooks works and when to use them in your projects.
Let’s get started!
- useState: useState is a hook that allows you to add state to functional components. It takes an initial value as an argument and returns an array with two elements: the current state value and a function that allows you to update the state.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
- useEffect: useEffect is a hook that allows you to perform side effects in functional components. It takes a callback function as its first argument and an optional array of dependencies as its second argument.
import React, { useEffect, useState } from 'react';
const Example = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
- useContext: useContext is a hook that allows you to access the nearest context in a functional component. It takes a context object as an argument and returns the current context value.
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
const ThemedButton = () => {
const theme = useContext(ThemeContext);
return (
<button style={{ backgroundColor: theme.background, color: theme.text }}>
Themed Button
</button>
);
};
- useReducer: useReducer is a hook that allows you to manage complex state logic in functional components. It takes a reducer function and an initial state as arguments and returns the current state and a dispatch function.
import React, { useReducer } from 'react';
const initialState = { count: 0 };
const reducer = (state, action) => {
switch(action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};
- useCallback: useCallback is a hook that memoizes a callback function and prevents unnecessary re-renders in functional components.
import React, { useCallback, useState } from 'react';
const MemoizedCallback = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
- useMemo: useMemo is a hook that memoizes an expensive computation and prevents unnecessary re-renders in functional components.
import React, { useMemo, useState } from 'react';
const MemoizedValue = () => {
const [count, setCount] = useState(0);
const squaredCount = useMemo(() => {
return count ** 2;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<p>Squared Count: {squaredCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
- useRef: useRef is a hook that allows you to create a mutable reference in functional components. It returns a mutable ref object that persists for the entire lifetime of the component.
import React, { useEffect, useRef } from 'react';
const AutoFocusInput = () => {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
};
- useImperativeHandle: useImperativeHandle is a hook that allows you to customize the instance value that is exposed to parent components when using forwardRef.
import React, { useImperativeHandle, useRef } from 'react';
const CustomInput = React.forwardRef((props, ref) => {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
- useLayoutEffect: useLayoutEffect is a hook that is similar to useEffect, but it runs synchronously after DOM mutations.
import React, { useLayoutEffect, useState } from 'react';
const Example = () => {
const [width, setWidth] = useState(window.innerWidth);
useLayoutEffect(() => {
const handleResize = () => {
setWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return <p>Window Width: {width}</p>;
};
- useDebugValue: useDebugValue is a hook that allows you to annotate custom hooks with a label that will be displayed in React DevTools.
import { useDebugValue } from 'react';
const useCustomHook = (value) => {
useDebugValue(value > 0 ? 'Positive' : 'Negative');
return value;
};
That’s it! You have now learned all about React hooks and how to use them effectively in your projects. Remember to practice using these hooks in your own projects to solidify your understanding. Happy coding!
👉Get Certified for react hooks course: https://quiz.greatstack.dev/rhks
Lopez Donald Hernandez Matthew Rodriguez Brenda
I need all the examples code for future reference
Plz provide git link
27:28
Why you are using count as a callback like count=>count+1
Its a real Gem !! best explaination on hooks, great way of teaching– starts with a problem –> makes us realise why we need any particular hook–> explains it clearly
what is major diff between redux and useContext hook
Is there an english version ?
Nice sir Make some video on react native your teaching styles is too good
Please make more series like that for javascript and react and redux too
can you use appwrite as a database and nodejs i hope you'll notice me
thanks
This content is really helpful for anyone who is looking for React Hooks or even the beginners. Thanks for sharing this AMAZING Simple content…!
nice explain sir👌
bestest react hooks vdo ever
thanks a lot.❤
very beautifully crafted videos 🙏 you are our custom Hook 😊😊🎉
Sir make the complete video on React router and nested routing plz plz
Do tutorial on react native and flutter.
In my 2 years in React JS. This is my first time I understand react hooks really well. Thank you for your well explained tutorial.