Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding useEffect hook #48

Open
zbzalex opened this issue Feb 3, 2023 · 1 comment
Open

Adding useEffect hook #48

zbzalex opened this issue Feb 3, 2023 · 1 comment

Comments

@zbzalex
Copy link

zbzalex commented Feb 3, 2023

  1. add global variable
let pendingEffects = []
  1. cerate a hook and add effects tag
function useEffect(fn, deps) {
            const hook = {
                tag: "EFFECT",
                fn,
                deps,
            }

            wipFiber._hooks.push(hook)
            hookIndex++
}
  1. modify performUnitOfWork function
if (isFunctionComponent) {
...
Object .keys(wipFiber._hooks)
                    .filter(hookIndex => wipFiber._hooks[hookIndex].tag === "EFFECT")
                    .forEach(hookIndex => {
                        const oldHook =
                            wipFiber.alternate &&
                            wipFiber.alternate._hooks &&
                            wipFiber.alternate._hooks[hookIndex]

                        const hook = wipFiber._hooks[hookIndex]
                        const depsChanged = (prev, next) => (_, index) => prev[index] !== next[index];
                        if (hook.deps.length === 0 && !oldHook
                            || oldHook && (oldHook.deps.length !== hook.deps.length
                                || oldHook && hook.deps.filter(depsChanged(oldHook.deps, hook.deps)).length !== 0)) {
                            pendingEffects.push(hook.fn)
                        }
                    })
...
  1. go to commitRoot function
...
pendingEffects.forEach(it => it()) // call pending effects after render
@zbzalex
Copy link
Author

zbzalex commented Feb 3, 2023

Modification project https://github.com/zbzalex/react-lite

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant