2024-05-01
2722
#react
Ohans Emmanuel
11894
May 1, 2024 â‹… 9 min read

How to access previous props or state with React Hooks

Ohans Emmanuel Visit me at ohansemmanuel.com to learn more about what I do!

Recent posts:

Rxjs Adoption Guide: Overview, Examples, And Alternatives

RxJS adoption guide: Overview, examples, and alternatives

Get to know RxJS features, benefits, and more to help you understand what it is, how it works, and why you should use it.

Emmanuel Odioko
Jul 26, 2024 â‹… 13 min read
Decoupling Monoliths Into Microservices With Feature Flags

Decoupling monoliths into microservices with feature flags

Explore how to effectively break down a monolithic application into microservices using feature flags and Flagsmith.

Kayode Adeniyi
Jul 25, 2024 â‹… 10 min read
Lots of multi-colored blue and purplish rectangles.

Animating dialog and popover elements with CSS @starting-style

Native dialog and popover elements have their own well-defined roles in modern-day frontend web development. Dialog elements are known to […]

Rahul Chhodde
Jul 24, 2024 â‹… 10 min read
Using Llama Index To Add Personal Data To Large Language Models

Using LlamaIndex to add personal data to LLMs

LlamaIndex provides tools for ingesting, processing, and implementing complex query workflows that combine data access with LLM prompting.

Ukeje Goodness
Jul 23, 2024 â‹… 5 min read
View all posts

17 Replies to "How to access previous props or state with React Hooks"

  1. You can’t use useEffect hook for this case because the effect might run after several renders asynchronously.
    For this case you should use useLayoutEffect hook which runs immediately after each render and in addition this logic doesn’t block painting then it’s fine to use it.

  2. I don’t want to come off rude, but your explanation is wrong.

    useEffect, yes will be run async, but it’ll run after the render NOT “several renders”.

    useLayoutEffect is pointless here since we aren’t reaching to the DOM for anything. Like you said, no painting. We really don’t get any added advantage using useLayoutEffect. Also, we intentionally want to run the side effect AFTER render so we save the previous value, hence using useEffect. Read some more here: https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state

  3. In usePrevious, shouldn’t the useEffect have a dependency on value? Otherwise if the component is re-rendered due to a different state change, in the next render, previousValue will equal value, right? Or am I missing something?

    1. Hi Aziz. This is correct, but also how the hook would work. It should return previous value related to previous renders. Regardless of how the render came about.

      Yes, you can put “value” in the dependency array – that’s a different use case but equally valid.

  4. Hey there!

    You’re explanation is really great such as this article. I like it very much, it helped me to break down things. However there might be a slight mistake in the article?

    “(4) The useEffect call is NOT invoked. Instead, the return value of the custom Hook is invoked.”

    Well I think it’s actually invoked… so JavaScript doesn’t magically skip this part, it executes top to bottom right? So the useEffect() actually invoked, but it’s parameter is an anonymus function: () => { ref.current = value }. And that inner function only gets invoked after the render part, because useEffect “smart” enough to know that right?

    Is that right to assume this way?

  5. I did the same thing and the previous prop and current props is the same. it shows the same value.
    i use reduxstore to manage the state in the component.

  6. No it is actually skipped and ran after the component is rendered, i.e. after the return statement.

    Try this:
    1. Put a console.log(“inside useEffect”) statement inside the useEffect()
    2. A hello() function with console.log(“inside hello”) inside the return statement in the component

    In the console, “inside hello” will appear before “inside useEffect”.

    Try and run the code snippet below. It is not inside a separate hook but the logic is same.

    import React, { useEffect } from “react”;

    export default function App() {
    const hello = () => {
    console.log(“inside hello”);
    };

    useEffect(() => {
    console.log(“inside useEffect”);
    });

    return {hello()};
    }

    Hope I answered your question.

  7. Excellent explanation of extremely opaque topic. It’s basically how I feel about hooks. They’re simple to use unless you want to understand what you’re doing. I like typing less but I miss the clarity of the old ways.

  8. usePrevious hook storing previous value if its object. its getting updated to new value on every rerender. I have used JSON.stringify to convert object to string and stored in usePrevious. in this way its working

  9. 1st example (which doesn’t work), can we assign a ref to a value ?

    you comment
    //assign the ref’s current value to the count Hook

    Where in fact you assign the state (not hook) value to a ref which doesnt make sense unless its a ref type not a value.

    in fact you are doing in useEffect like if it was in a react element initializer attribut : ref={refname}

Leave a Reply