Skip to content

Instantly share code, notes, and snippets.

@j0053f
Last active July 12, 2022 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j0053f/5cdf64149605aaf281954320c895b5b0 to your computer and use it in GitHub Desktop.
Save j0053f/5cdf64149605aaf281954320c895b5b0 to your computer and use it in GitHub Desktop.
closure concept usage in react hooks context.
function Func() {
let a = 0;
const callback = (a) => () => console.log(a);
setTimeout(callback(a), 1000);
a += 1;
console.log(a);
}
Func();
/*
the nature of closure is to keep knowledge of what the closed-over values
were when the closure was created - called "capturing".
react useEffect(callback, dependencies) hook behave like this!
the values that callback is closed-over are a list of component's state and props.
check this: https://reacttraining.com/blog/useEffect-is-not-the-new-componentDidMount/
*/

"The difference is that useEffect captures the value of count when the effect gets created." notice to the difference of current value and captured value.

captured value of the value (state)

setValue(value+1)

current value of the value (state)

setValue(value=>value+1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment