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:

A Guide To The React UseReducer Hook

A guide to the React useReducer Hook

The useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.

Ejiro Asiuwhu
Oct 10, 2024 â‹… 13 min read
Using The Built-In SQLite Module In Node.js

Using the built-in SQLite module in Node.js

Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.

Amazing Enyichi Agu
Oct 10, 2024 â‹… 12 min read
Understanding and supporting zoom behaviors on the web

Understanding and supporting zoom behaviors on the web

Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.

Fimber Elemuwa
Oct 9, 2024 â‹… 7 min read
Comedy and tragedy masks symbolizing Playwright Extra's ability to extend Playwright with customizable plugins for both stealth and interactive browser automation tasks.

Playwright Extra: extending Playwright with plugins

Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]

Antonello Zanini
Oct 8, 2024 â‹… 9 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