How to set initial state for useState Hook in jest and enzyme?

You can mock React.useState to return a different initial state in your tests: // Cache original functionality const realUseState = React.useState // Stub the initial state const stubInitialState = [‘stub data’] // Mock useState before rendering your component jest .spyOn(React, ‘useState’) .mockImplementationOnce(() => realUseState(stubInitialState)) Reference: https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga

Why can’t React Hooks be called inside loops or nested function?

The reference states the actual cause, By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. and provides the example that shows why this is important. Loops, conditions and … Read more

React Hooks – How do I implement shouldComponentUpdate?

In a comment above Gabriele Petrioli links to the React.memo documentation that explains how to implement shouldComponentUpdate. I was googling combinations of shouldComponentUpdate + useEffect + “react hooks”, and this came up as the result. So after solving my problem with the linked documentation I thought I would bring the information here as well. This … Read more

How do I window removeEventListener using React useEffect

You can put the handleKeyUp function inside of the function given to useEffect (which is the recommended way of doing it according to the official documentation) and only add the listener and return a cleanup function when collapsed is false. useEffect(() => { if (collapsed) { return; } function handleKeyUp(event) { switch (event.key) { case … Read more

Uncaught Invariant Violation: Rendered more hooks than during the previous render

I faced the same issue. What I was doing was something like this: const Table = (listings) => { const {isLoading} = useSelector(state => state.tableReducer); if(isLoading){ return <h1>Loading…</h1> } useEffect(() => { console.log(“Run something”) }, []) return (<table>{listings}</table>) } I think what was happening was that on the first render, the component returned early and … Read more

When to use useCallback, useMemo and useEffect?

A short explanation. useEffect It’s the alternative for the class component lifecycle methods componentDidMount, componentWillUnmount, componentDidUpdate, etc. You can also use it to create a side effect when dependencies change, i.e. “If some variable changes, do this”. useCallback On every render, everything that’s inside a functional component will run again. If a child component has … Read more

tech