DEV Community

Cover image for React Hooks: When Not to Use useEffects

React Hooks: When Not to Use useEffects

Viviana Yanez on February 15, 2024

I am working on a client-side application using React and Firebase. This week, I paired with another team member to add a new feature allowing user...
Collapse
 
imhollymolly profile image
imhollymolly

This is where memoization is useful. Memoization is the concept of keeping memory of a function return value to avoid repeated calls to functions that process the same input.

function Home({ data }) {
    const [name, setName] = React.useState("");
    const isLastItemAdded = React.useMemo(() => data[data.length - 1] == name, [data, name]);

    // isLastItemAdded is a boolean. It will be true if name is the loosely equal to the last item inside of the data array prop.

    const addToList = (e) => {
        e.preventDefault();
        isLastItemAdded ? notify() : displayErrors();
    }

    return (
        <div className="Home">
            <form onSubmit={addToList}>
                <label htmlFor="new-list-name">Create a new list</label>
                <input
                    type="text"
                    id="new-list-name"
                    value={name}
                    onChange={e => setName(e.currentTarget.value)}
                />
                <button type="submit">Create list</button>
            </form>
            <ul>
                {data.map((item, i) => <li key={i}>{item}</li>)}
            </ul>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

react.dev/reference/react/useMemo

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
Enter fullscreen mode Exit fullscreen mode

On the initial render, useMemo returns the result of calling the callback. During next renders, it will either return an already stored value from the last render if the dependencies haven’t changed, or call the callback again and return the result.

Be aware that proper structure of component architecture would have got you to handle that logic from the parent component instead.

Collapse
 
disturbedneo profile image
DisturbedNeo

Since you already have a parent component passing "data" down to your Home component, you can also pass an "onSubmit" function as a prop that you add to the form element, and remove all the internal state from Home.

The parent component handles managing the state, including updating the list and displaying a success message, and the child becomes a "dumb" component whose sole responsibility is displaying whatever data it is given.

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

Totally agree here !

Collapse
 
get_pieces profile image
Pieces 🌟

Great article! πŸ”₯