Post by account_disabled on Sept 10, 2023 12:58:51 GMT 2
React maintains its leading position among JavaScript UI frameworks. There is a lot of development going on in React, but the most important change over the past few years is the shift to functional components. Functional components rely on hooks for much of their functionality. The most common hook is useState, but there are many more.
Introducing 8 useful React hooks that are not widely known.
useReducer
useState is a hook that everyone knows. This is Phone Number List because member variables for state storage, which are an essential function of class-based components, are replaced with functional variables. The useReducer hook has similar functionality, but is suitable for more complex scenarios where there are many elements involved in state transitions and explicit transitions are beneficial to the application. The useReducer hook is a hook inspired by Redux’s reducer. It can be seen as positioned between the simplicity of useState and the complexity of state management systems such as Redux.
<Example 1> takes text from an input box and has the user click a button to display this text in all uppercase or all lowercase. The code declares a new reducer with const [state, dispatch] = useReducer(reducer, initialState); useReducer receives a reducer function and initialstate and returns an array. Deconstruct this array into state and dispatch variables.
The reducer itself is defined as const reducer = (state, action) => and provides a two-argument function. Whenever the dispatch function is called in your code, it passes an action object with the current state. Here, the action object has a type field, which we use to determine how to transform the state. In moderately complex applications, useReducer can help manage complexity, and it can also be shared across applications using context. If managing useState is difficult due to the complexity of your application, the useReducer hook can help.
useCallback
The useCallback hook is a performance hook. It takes a function and ensures that only one version is returned and reused by all callers. If your function is expensive and is called repeatedly by loops or child components, you can get a significant performance boost with the useCallback hook. This type of optimization is called memoizing functions.
In <Example 2>, useCallback is used to use the same function across many items in the list. There is also a live JSFiddle example .
Create a new memoized function incrementCounter using React.useCallback(). You can use a memoized function as a general function in the onClick handler of the list. useCallback() takes a function as the first argument. You can do whatever you need to do within this function. The important difference is that React returns the cached value of a function unless something changes in the list of dependency variables (the counter variable in Example 2).
This is very powerful when expensive functions need to be shared between multiple callers, especially child components. For example, in useMemo, which we will look at next, you can see that useCallback hides the function itself. In other words, useCallback prevents the actual function from being recreated every time it appears, and only recreates it when necessary.
use Memo
The useMemo hook is the sister of useCallback. useCallback caches the function and useMemo caches the function return value. It's a subtle but important difference. When should you use useMemo rather than useCallback? The answer is to use useMemo when available and useCallback when necessary. useCallback is advantageous to avoid performance degradation resulting from creating the function itself in rendering. This is because useMemo does not prevent the function from being recreated wherever it appears. However, useMemo ensures that the function returns the cached value if the dependencies have not changed.
You can see an example of useMemo in <Example 3>. You can also see examples on live JSFiddle .
In <Example 3>, there is computeExpensiveValue, a function with large computing costs. This function relies on a single input, count. You can use computeExpensiveValue(count), [count]) to tell React to run this function only if count has changed, otherwise return the cached calculation. Here too, the distinction with useCallback is not clear. The important difference is that useCallback is a hook used when the function itself is repeatedly instantiated, causing performance degradation. Otherwise, useMemo is a better choice.
useContext
In React, context is a mutable scope that exists outside of a component and can be accessed by all components. In other words, it is a quick and easy global space for application-wide data. For complex scenarios it may be better to use a formal data store like Redux, but for many use cases context is sufficient. The useContext hook is how a functional component interacts with its context.
In <Example 4>, there are two components, Speak and Happy, and App, the application parent component, uses these two. The user can toggle between dog and cat states, and child components reflect that choice via the global context. For example, wagging its tail or making noises. You can check out the live JSFiddle of this example.
The useRef hook manages references outside of the render cycle. useState forces the React engine to render when changed, whereas useRef does not. The useRef hook can be said to be a special area set aside on one side of React, and serves as a notification that 'this variable is special and is not part of the Reactive UI.' The most common use case for useRef is to gain direct access to the DOM and its API. In general, this is something to avoid in a reactive way of thinking and everything should be processed through a reactive engine, but there are cases where it is unavoidable.
In fact, in <Example 5>, when the button is clicked, a useRef hook is used to store a reference to the input field, a DOM method is used to set focus, and the value is set to “Something amazing”. There is a JSFiddle for a useRef example.
Introducing 8 useful React hooks that are not widely known.
useReducer
useState is a hook that everyone knows. This is Phone Number List because member variables for state storage, which are an essential function of class-based components, are replaced with functional variables. The useReducer hook has similar functionality, but is suitable for more complex scenarios where there are many elements involved in state transitions and explicit transitions are beneficial to the application. The useReducer hook is a hook inspired by Redux’s reducer. It can be seen as positioned between the simplicity of useState and the complexity of state management systems such as Redux.
<Example 1> takes text from an input box and has the user click a button to display this text in all uppercase or all lowercase. The code declares a new reducer with const [state, dispatch] = useReducer(reducer, initialState); useReducer receives a reducer function and initialstate and returns an array. Deconstruct this array into state and dispatch variables.
The reducer itself is defined as const reducer = (state, action) => and provides a two-argument function. Whenever the dispatch function is called in your code, it passes an action object with the current state. Here, the action object has a type field, which we use to determine how to transform the state. In moderately complex applications, useReducer can help manage complexity, and it can also be shared across applications using context. If managing useState is difficult due to the complexity of your application, the useReducer hook can help.
useCallback
The useCallback hook is a performance hook. It takes a function and ensures that only one version is returned and reused by all callers. If your function is expensive and is called repeatedly by loops or child components, you can get a significant performance boost with the useCallback hook. This type of optimization is called memoizing functions.
In <Example 2>, useCallback is used to use the same function across many items in the list. There is also a live JSFiddle example .
Create a new memoized function incrementCounter using React.useCallback(). You can use a memoized function as a general function in the onClick handler of the list. useCallback() takes a function as the first argument. You can do whatever you need to do within this function. The important difference is that React returns the cached value of a function unless something changes in the list of dependency variables (the counter variable in Example 2).
This is very powerful when expensive functions need to be shared between multiple callers, especially child components. For example, in useMemo, which we will look at next, you can see that useCallback hides the function itself. In other words, useCallback prevents the actual function from being recreated every time it appears, and only recreates it when necessary.
use Memo
The useMemo hook is the sister of useCallback. useCallback caches the function and useMemo caches the function return value. It's a subtle but important difference. When should you use useMemo rather than useCallback? The answer is to use useMemo when available and useCallback when necessary. useCallback is advantageous to avoid performance degradation resulting from creating the function itself in rendering. This is because useMemo does not prevent the function from being recreated wherever it appears. However, useMemo ensures that the function returns the cached value if the dependencies have not changed.
You can see an example of useMemo in <Example 3>. You can also see examples on live JSFiddle .
In <Example 3>, there is computeExpensiveValue, a function with large computing costs. This function relies on a single input, count. You can use computeExpensiveValue(count), [count]) to tell React to run this function only if count has changed, otherwise return the cached calculation. Here too, the distinction with useCallback is not clear. The important difference is that useCallback is a hook used when the function itself is repeatedly instantiated, causing performance degradation. Otherwise, useMemo is a better choice.
useContext
In React, context is a mutable scope that exists outside of a component and can be accessed by all components. In other words, it is a quick and easy global space for application-wide data. For complex scenarios it may be better to use a formal data store like Redux, but for many use cases context is sufficient. The useContext hook is how a functional component interacts with its context.
In <Example 4>, there are two components, Speak and Happy, and App, the application parent component, uses these two. The user can toggle between dog and cat states, and child components reflect that choice via the global context. For example, wagging its tail or making noises. You can check out the live JSFiddle of this example.
The useRef hook manages references outside of the render cycle. useState forces the React engine to render when changed, whereas useRef does not. The useRef hook can be said to be a special area set aside on one side of React, and serves as a notification that 'this variable is special and is not part of the Reactive UI.' The most common use case for useRef is to gain direct access to the DOM and its API. In general, this is something to avoid in a reactive way of thinking and everything should be processed through a reactive engine, but there are cases where it is unavoidable.
In fact, in <Example 5>, when the button is clicked, a useRef hook is used to store a reference to the input field, a DOM method is used to set focus, and the value is set to “Something amazing”. There is a JSFiddle for a useRef example.