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:

Rust logo over black marble background.

Handling memory leaks in Rust

Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.

Ukeje Goodness
Nov 20, 2024 â‹… 4 min read
Robot pretending to be a person.

Using curl-impersonate in Node.js to avoid blocks

Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.

Antonello Zanini
Nov 20, 2024 â‹… 13 min read
Solving Eventual Consistency In Frontend

Solving eventual consistency in frontend

Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.

Kayode Adeniyi
Nov 19, 2024 â‹… 6 min read
How To Use Lazy Initialization Pattern With Rust 1.80

How to use the lazy initialization pattern with Rust 1.80

Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.

Yashodhan Joshi
Nov 18, 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