Conquer the React hooks
The Things you need to know about React hooks that can help you to conquer the React Hooks concept.
Every single time you go out to the internet and search for react hooks but you can't understand react hooks efficiently so my friend this blog is for you which can help you to conquer the react hooks concept š.
So enjoy this blog from which you gather information about react hooks.
Here are some basic stuff about React Hooks
React Hooks are a feature introduced in React version 16.8. They allow you to use state and other React features in functional components without the need for class components. This simplifies the syntax and structure of React components.
You see that currently, all the people are using functional components so you need state management that's why you need to learn about React hooks. React Hooks also provide a way to share stateful logic between components, which can further simplify your code and reduce duplication.
Basic React Hooks
Here are some basic and commonly used React hooks.
- useState : This hook allows you to use state in functional components. It takes an initial value as an argument and returns an array with two elements: the current state and a function to update the state. Here's an example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
ā¢ In this example, we use the useState hook to initialize a state variable called count
0. We also define a function called handleClick
that updates the count
variable using the setCount
function. Finally, we render the count
variable and a button that calls the handleClick
function when clicked.
useEffect : This hook allow you to perform side effects in your components. It takes a function as its first argument and an optional array of dependencies as its second argument. Here are some examples :
- Example one :
import React, { useState, useEffect } from 'react';
function Data() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data.map(item => (
<div key={item.id}>
<h3>{item.title}</h3>
<p>{item.body}</p>
</div>
))}
</div>
);
}
export default Data;
ā¢ In this example, the useEffect
hook is used to fetch data from an API and set it as the state of the component. The second argument of useEffect
is an empty array, which means that the effect will only be run once when the component is mounted. In this example, we don't pass a dependency array.
Example two :
import React, { useEffect } from 'react'; function Title({ title }) { useEffect(() => { document.title = title; }, [title]); return null; } export default Title;
ā¢ In this example, the
useEffect
hook is used to set the document title based on thetitle
prop. The effect is run every time thetitle
prop changes. The component returnsnull
because it doesn't need to render anything. You see that we are passing the title as a dependency array.
- useContext : This hook allows you to use context in functional components. It takes a context object as its argument and returns the current value of the context. With the help of this hook, we handle the prop drilling. Here's an example:
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemeToggle() {
const theme = useContext(ThemeContext);
return (
<button
style={{ backgroundColor: theme === 'dark' ? '#333' : '#fff', color: theme === 'dark' ? '#fff' : '#333' }}
onClick={() => {
theme === 'dark' ? setTheme('light') : setTheme('dark');
}}
>
Toggle theme
</button>
);
}
ā¢ In this example, we create a context object called ThemeContext
with a default value of light
. We also create a component called ThemeToggle
that uses the useContext hook to get the current value of the ThemeContext
context. Finally, we render a button that toggles the theme when clicked.
Advanced React Hooks
You see that basic React hooks which used commonly. Now we see some advanced React hooks.
useReducer : The
useReducer
hook is an alternative touseState
that allows you to manage complex state logic in your application. It takes a reducer function and an initial state as arguments and returns the current state and a dispatch function to update the state. Here's an example :import React, { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </> ); }
ā¢ This code is an example of using the
useReducer
hook in a React component to manage state. Thereducer
function takes two arguments: the current state and an action object that describes how to update the state. In this case, the action object has atype
property that can be either "increment" or "decrement", and thereducer
function returns a new state object that either increments or decrements thecount
property of the previous state.ā¢ In the
Counter
component, theuseReducer
hook is used to initialize thestate
object with acount
property set to 0, and to get thedispatch
function that is used to update the state by dispatching actions to the reducer. TheCount
is displayed using thestate.count
value, and theonClick
handlers of the+
and-
buttons call thedispatch
function with the corresponding action type to update the state.ā¢ Overall, this code demonstrates how the
useReducer
hook can simplify state management in a React component by encapsulating the logic for updating state in a separate function.useCallback : The
useCallback
hook is used to memoize functions so that they do not have to be recreated every time a component re-renders. It takes a function and an array of dependencies as arguments and returns a memoized function. Here's an example :function MemoizedComponent({ onButtonClick }) { const handleClick = useCallback(() => { onButtonClick(); }, [onButtonClick]); return <button onClick={handleClick}>Click me</button>; }
ā¢ In this example we defines a React functional component called
MemoizedComponent
that takes a prop calledonButtonClick
. Within the component, theuseCallback
hook is used to memorize thehandleClick
function so that it does not have to be recreated every time the component re-renders. ThehandleClick
function simply calls theonButtonClick
function that was passed in as a prop. Finally, thehandleClick
function is passed as a callback to theonClick
event of a button element that is rendered by the component. When the button is clicked, thehandleClick
function is called, which in turn calls theonButtonClick
function.useMemo : The
useMemo
hook is used to memoize values so that they do not have to be recalculated every time a component re-renders. It takes a function and an array of dependencies as arguments and returns a memoized value. Here's an example :function ExpensiveCalculation({ value }) { const result = useMemo(() => { // Perform expensive calculation here return value * 2; }, [value]); return <div>Result: {result}</div>; }
ā¢ This code defines a component called
ExpensiveCalculation
that takes a prop calledvalue
. Within the component, theuseMemo
hook is used to perform an expensive calculation (multiplyingvalue
by 2) and memoize the result so that it does not need to be recalculated every time the component re-renders. The memoized value is then returned and displayed in the component using theResult: {result}
syntax.ā¢ In summary, this component optimizes performance by avoiding unnecessary recalculation of expensive calculations when the component re-renders.
useRef : The
useRef
hook is used for accessing DOM nodes or storing mutable values in your application. It returns a mutable ref object that can be used to store and update values. The value of the ref persists between renders. Here's an example :function MyComponent() { const inputRef = useRef(null); function focusInput() { inputRef.current.focus(); } return ( <> <input type="text" ref={inputRef} /> <button onClick={focusInput}>Focus input</button> </> ); }
ā¢ This code defines a functional component called
MyComponent
that renders an input element and a button. It uses theuseRef
hook to create a reference to the input element, which is assigned to theinputRef
constant.ā¢ The
focusInput
function is defined insideMyComponent
and uses thecurrent
property of theinputRef
object to access the actual DOM node of the input element and call itsfocus()
method, which sets the focus to the input.ā¢ The button element has an
onClick
event handler that calls thefocusInput
function when clicked, which triggers the focus of the input element.ā¢ In summary, this code creates a component that allows the user to focus on an input element by clicking a button using the
useRef
hook to access the input element and itsfocus()
method.
Conclusion
Using React Hooks can simplify your code and make it easier to reason about, as it encourages a more functional programming style. However, it's important to use them correctly and understand their limitations, as improper use can lead to unexpected behavior or performance issues. You should build customer hooks that can help you to build reusable functions that a React JS software developer can use to add special and unique functionality to the React applications.