Skip to content

Instantly share code, notes, and snippets.

@disusered
Last active July 13, 2020 16:09
Show Gist options
  • Save disusered/aaad5b1287a63020d83b09200e372a48 to your computer and use it in GitHub Desktop.
Save disusered/aaad5b1287a63020d83b09200e372a48 to your computer and use it in GitHub Desktop.
/**
* Here we have a component with a useEffect hook. Even though we've told React
* that the hook should only fire when firstHookDependency or secondHookDependency change,
* React is still going to fire this hook on every render. Explain in a few sentences how you would rewrite
* firstHookDependency and secondHookDependency to ensure that the useEffect hook only fires
* when these values change.
* */
const Component = () => {
// Function is recreated on every render, useCallback memoizes the callback. Alternatively, based on the
// function's dependencies it may be hoisted outside the component
const firstHookDependency = useCallback(() => {});
const secondHookDependency = ['We', '💕', 'React'];
React.useEffect(() => {
console.log('Why will this console statement run?');
// Due to the shallow, static data structure, we can serialize and avoid more complex implementations
// With a more complex dependency, we can hoist it outside of the component definition, or with dynamic
// dependency we can memoize with `useMemo`
}, [firstHookDependency, JSON.stringify(secondHookDependency)]);
return (
// ...component details
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment