Dispatching actions inside inner functions of funtional component

Viewed 118

I read that inner functions in statefull functional component should be defined using useCallback when we use setState or that function is passed as prop to child component. But what about dispatching actions? Do we need to use 'useCallback' there also?

import React from "react";
import { logout } from "../../../../actions/auth";
import { useDispatch } from "react-redux";

function Navbar (props) {
    ...

    const dispatch = useDispatch();

    const handleClick = () => {
        dispatch(logout());
    }

    return (
       <div> 
         <button onClick={handleClick}>Logout</button> 
       </div>
    )
}
2 Answers

So first of all you need to know why you sometimes need useCallback around your functions and listeners.

The powerful useMemo and useCallback hooks create a value which is referentially stable (prev === current) between re-renders under the condition that the inputs (or “dependencies”) arrays doesn’t change its values (again, referentially). This allows children components you pass your values to to memoize themselves with React.memo and similar tools.

Why would you need to let them memoize? For performance reasons. And the first rule of performance optimization is you don’t optimize prematurely. So, do not blindly wrap everything in useCallback and useMemo: write your code and only once you reach some performance bottleneck investigate and eventually solve with those hooks.

To answer your question, do dispatch functions need to be wrapped? As I infer from your code we are talking about React Redux’ dispatch. The answer is no: React Redux dispatch, useReducer’s dispatch, useState’s updater function are all referentially stable.

dispatch does not effect to your inner functions. Your inner functions will be re-created when you create it without useCallback or with useCallback but dependencies changed

You can put dispatch as a dependency of useCallback and use it like normal function

const handleClick = useCallback(() => {
    dispatch(logout());
}, [dispatch])
Related