最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get latest component variable value in 'useEffect' hook? - Stack Overflow

programmeradmin2浏览0评论

How to use an updated value of a variable (declared at ponent scope) in each 'useEffect'?

import React, { useState, useEffect } from 'react';

export default function Count() {

    const [count, setCount] = useState(0);

    let a = 10;

    useEffect(() => {
        console.log('after 1st render', a);
        a++;
        console.log(a);
        return () => { console.log('cleanup - on unmount.') }
    }, [a]);

    useEffect(() => {
        console.log('only when count changes', a);
        a++;
        return () => { console.log('count cleanup', a) }
    }, [count, a]);

    return <div>
        <p>Count : {count}</p>
        <button onClick={() => { console.log('at global', a); setCount(count + 1) }}>Click</button>
    </div>
}

output
after 1st render 10
11
only when count changes 11
at global 12
count cleanup 12
only when count changes 10

Now, What I don't understand from this output is the last line which outputs the value of 'a' as 10.

Every time a useEffect gets called, it creates a new copy of the function provided, and it also calls the cleanUp function right?.

when I click the button the count changes, the previous cleanUp gets called and clean that 'useEffect' behaviour which sets the value of 'a' from 11 to 12, and then the current 'useEffect' called with value 10. it should print the value 11. ? can anyone please clarify this.

How to use an updated value of a variable (declared at ponent scope) in each 'useEffect'?

import React, { useState, useEffect } from 'react';

export default function Count() {

    const [count, setCount] = useState(0);

    let a = 10;

    useEffect(() => {
        console.log('after 1st render', a);
        a++;
        console.log(a);
        return () => { console.log('cleanup - on unmount.') }
    }, [a]);

    useEffect(() => {
        console.log('only when count changes', a);
        a++;
        return () => { console.log('count cleanup', a) }
    }, [count, a]);

    return <div>
        <p>Count : {count}</p>
        <button onClick={() => { console.log('at global', a); setCount(count + 1) }}>Click</button>
    </div>
}

output
after 1st render 10
11
only when count changes 11
at global 12
count cleanup 12
only when count changes 10

Now, What I don't understand from this output is the last line which outputs the value of 'a' as 10.

Every time a useEffect gets called, it creates a new copy of the function provided, and it also calls the cleanUp function right?.

when I click the button the count changes, the previous cleanUp gets called and clean that 'useEffect' behaviour which sets the value of 'a' from 11 to 12, and then the current 'useEffect' called with value 10. it should print the value 11. ? can anyone please clarify this.

Share Improve this question asked Jul 28, 2019 at 12:10 rohit rohit 5381 gold badge5 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

On every render, all Count body executed, therefore changing state via button click will result in calling let a = 10 and resetting the value of a.

In other words, the local variable a lifetime is until the next render.

To get desired behavior, try using a reference with useRef.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the ponent.

const [count, setCount] = useState(0);

const aRef = useRef(10);
let a = 10;

useEffect(() => {
  console.log("after 1st render", a);
  a++;
  aRef.current++;
  console.log(a);
  return () => {
    console.log("cleanup - on unmount.");
  };
}, [a]);

useEffect(() => {
  console.log("only when count changes", a);
  console.log("only when count changes - ref", aRef.current);
  a++;
  aRef.current++;
  return () => {
    console.log("count cleanup", a);
  };
}, [count, a]);

Will result:

only when count changes 10

only when count changes - ref 12


Read more at uses of useEffect

发布评论

评论列表(0)

  1. 暂无评论