M
M
Max Zhukov2019-04-11 17:22:22
React
Max Zhukov, 2019-04-11 17:22:22

How to use useCallback handler in useEffect?

After the widgets changes, the handleTopologySelect reference is changed, hence useEffect is called (memoize-one cannot store the handlers themselves in the cache) and so on, how can this be avoided?

const getMemoWidgets = memoizeOne(widgets => widgets, isDeepEqual);

    const handleTopologySelect = useCallback((selectedNode) => {
        const newWidgets = widgets.map((widget) => {
            if (widget.isTopology) {
                const { props: widgetProps } = widget;
                return {
                    ...widget,
                    props: {
                        ...widgetProps,
                        nodes: widgetProps.nodes.map((node) => {
                            if (node.id === selectedNode.id) {
                                return { ...node, isSelected: !selectedNode.isSelected };
                            }
                            return node;
                        })
                    }
                };
            }
            return widget;
        });
        setWidgets(getMemoWidgets(newWidgets));
    }, [widgets]);

    useEffect(() => {
        const newWidgets = widgets
            .map((widget) => {
                if (widget.isTopology) {
                    return {
                        ...widget,
                        props: { ...props[widget.id], onSelect: handleTopologySelect }
                    };
                }
                return {
                    ...widget,
                    props: { ...props[widget.id] }
                };
            });
        setWidgets(getMemoWidgets(newWidgets));
    }, [handleTopologySelect, props, widgets]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-11
@rockon404

1. A memorized function must be initialized outside of the render call, otherwise it will be re-created every render.
2. Passing the handler to the array of the second argument to useEffect is meaningless, since you are passing widgets there.
3. It is not clear what your code does and what behavior you want to achieve, as the example is taken out of context.
4. It's not clear what's stopping you from using classes. You are only making simple things more difficult.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question