Various React Hooks Every React Developer Should Know

Various React Hooks Every React Developer Should Know

React is an open-source JavaScript-based UI library. It is in trend for mobile and web app development. It follows the guidelines of component-based architecture. A component is a separate and reusable piece of code. The components can be of two types – class components and functional components.

Before React version 16.8, developers could handle state and other React features only using class components. But with version 16.8, React introduced a new pattern known as Hooks. With React Hooks, we can use state and other features in a functional component also. It fundamentally empowers developers to do functional programming in React.

There are some basic rules for hooks:

  • Hooks cannot be conditional.

  • Hooks will not work in React Class Component.

  • Hooks can be called only inside function components.

  • Hooks can call other Hooks.

Hooks are backward compatible; subsequently, it contains no breaking changes. Additionally, it doesn't supplant your insight into React concept.

Let's discuss the top react hooks that every developer should know in detail.

useState :

It is the most significant and frequently utilized hook. The purpose behind this hook is to deal with responsive information; any information that changes the application is called state; when any information changes, then React renders the UI again. The useState hook permits us to make state variables in a React function component.

When we make a state variable, we should give it a default value. We get that state variable as the principal value in an array system, which we can destructure and pronounce with const.

 const [count, setCount] = React.useState(0);

useEffect :

useEffect allows us to perform side effects in function parts. Aftereffects incorporate arriving at the rest of the world, like fetching information from a Programming API interface or working with the DOM(Document Object Model). Side effects are activities that can erratically change our component state.

React.useEffect(() => {
    alert('Hey, Nads here!');
});

// this will run, when the component is first initialized
React.useEffect(() => {
    alert('Hey, Nads here!');
}, []);

// this will run only when count state changes
React.useEffect(() => {
    fetch('nads').then(() => setLoaded(true));
}, [count]);

// this will run when the component is destroyed or before the component is removed from UI.
React.useEffect(() => {
    alert('Hey, Nads here');

    return () => alert('Goodbye Component');
});

useEffect acknowledges a callback function known as effect function, which will, as a matter of course, run each time the component re-renders. It permits us to carry out all lifecycle hooks inside a solitary capability API interface.

Read More: A 2K22 Comprehensive Guide to Web App Development

useMemo:

useMemo is the same as useCallback and further develops execution. In any case, it stores the consequences of costly activities rather than being for callbacks. useMemo permits us to memoize or recollect the result of expensive activities when they have been made for specific input sources.

This hook will assist you with upgrading computational expenses or further developing execution. It is, for the most part, utilized when we're expected to make costly estimations.

function useMemo() {

    const [count, setCount] = React.useState(60);

    const expensiveCount = useMemo(() => {
        return count**2;
    }, [count]) // recompute when count changes.
}

useCallback :

Callback functions are the name of functions that are "called back." It happens within a parent component. It is used for improving our component performance. The most well-known use is to have a parent component with a state variable, yet you need to refresh that state from child components.

function useCallbackDemo() {
    const [count, setCount] = useState(60);


    const showCount = React.useCallback(() => {
        alert(`Count ${count}`);
    }, [count])


    return <> <SomeChild handler = {showCount} /> </>
}

useCallback memoizes our callback capabilities so they are not reproduced/recreated on each re-render. Utilizing useCallback accurately can work on the performance of our application.

Read More: A Step-by-Step Guide to Mobile App Development Process

useContext :

This hook permits us to work with React's Context API interface, a mechanism/system to share data within its component tree without passing through props. It eliminates prop drilling. In some cases, going props through multiple components are acceptable; however, passing them through components that do not need them is redundant.

const AnsContext = createContext(ans);

function Exam(props) {
    return (
        // Any child component inside this component can access the value which is sent.
        <AnsContext.Provider value={ans.right}>
            <RightAns />
        </AnsContext.Provider>
    )
}

function RightAns() {
    // it consumes value from the nearest parent provider.
    const ans = React.useContext(AnsContext);
    return <p>{ans}</p>
    // previously we were required to wrap up inside the AnsContext.Consumer
    // but this useContext hook, get rids that.
}

Context helps pass props down numerous degrees of kid components from a parent part and sharing state across our application component tree. The useContext hook eliminates the strange-looking render props design expected in consuming React Context.

useReducer :

It does the same as setState; It's an alternate method for dealing with the state utilizing Redux Pattern. Rather than refreshing the state straightforwardly, we dispatch actions that go to a minimizer function, and this function sorts out some way to compute the upcoming new state.

function reducer(state, dispatch) {
    switch(action.type) {
        case 'increment':
            return state+1;
        case 'decrement':
            return state-1;
        default:
            throw new Error();
    }
}

function useReducer() {
    // state is the state we want to show in the UI.
    const [state, dispatch] = React.useReducer(reducer, 0);

    return (
        <>
        Count : {state}
        <button onClick={() => dispatch({type:'decrement'})}>-</button>
        <button onClick={() => dispatch({type:'increment'})}>+</button>
        </>
    )
}

It would help if you went after useReducer, not exactly useState around your application. It is helpful as a powerful method for overseeing states in smaller applications, as opposed to going after an outsider state in the state management library like Redux.

useRef :

Refs are a unique attribute available on all React components. This hook permits us to make a changeable item. It is utilized when the value continues to change, as on account of the useState hook, yet the thing that matters is it doesn't set off a re-render when the value varies. They permit us to refer to a given component/part when the part mounts.

function App() {
    const myBtn = React.useRef(null);
    const handleBtn = () => myBtn.current.click();
    return (
        <button ref={myBtn} onChange={handleBtn} >
        </button>
    )
}

It is helpful when we want to interact directly with an element. For example- to clear its value or focus it, as with an input.

The standard use case is to get HTML components from the DOM.

useRef permits us to utilize React refs without any problem. They are helpful when we need to collaborate with an element, for example, to clear its worth or center it, similarly to an input.

useLayoutEffect :

It works equivalent to the useEffect snare with one contrast; the callback will pursue run after rendering the component before the genuine updates have been painted on the screen.

 function useLayoutEffectDemo() {


    const myBtn = React.useRef(null);


    React.useLayoutEffect(() => {
        const rect = myBtn.current.getBoundingClientRect();
        // scroll position before the dom is visually updated
        console.log(rect.height);
    })
}

useDebugValue :

This hook doesn't appear legit, yet it permits us to characterize our custom labels in React Dev Tools, which help troubleshoot or debug. Assuming we have n number of parts that utilize similar rationale. We can independently characterize our function that can be used in different components, yet the critical thing here is we can debug things too.

 function useDisplayName() {
    const [displayName, setDisplayName] = React.useState();


    React.useEffect(() => {
        const data = fetchFromDatabase(props.userId);
        setDisplayName(data.displayName);
    }, []);


    React.useDebugValue(displayName ?? 'loading...');
    return displayName;
}

Custom Hooks

There may be a circumstance where you have utilized similar tedious and repetitive stateful rationale inside numerous components. So reference that rationale in each part; we can isolate that code in a document and use it any place we need.

That's it!!! If you wish to know more about Hooks & Hooks was created, then the best can be explained by looking back to the youtube video of Sophie Alpert's talk at React Conf 2018.

This guide helps you understand Hooks's basics and allows you to expand on these models and create new and unique things. Please drop a comment below or contact us for any questions or suggestions.

Thanks!!!

Did you find this article valuable?

Support Quokka Labs' Blogs by becoming a sponsor. Any amount is appreciated!