UI not getting updated using useReducer

Let’s say I have a reducer.js file that contains

export default function reducer(state, action) {
    let newState;
    switch (action.type) {
        case "REMOVE_GOAL":
            newState = state;
            newState.splice(action.payload.index, 1);
            console.log("Inside reducer state", newState);
            return newState;
        default:
            return state;
    }
}

Which I’m importing and using in something.js file

function Something() {
    const [state, dispatch] = useReducer(reducer, []);

    console.log("Inner state", state);
    useEffect(() => {}, [state]);

    return (
        <>
            <div>Skipping things to keep short</div>
            <AnotherFile
                state={state}
                dispatch={dispatch}
            />
        </>
    );
}

return default Something;

And my final component anotherfile.js which is showing everything on my UI.

function AnotherFile({ state, dispatch }) {

    console.log("Outer state", state);
    useEffect(() => {}, [state]);

    return (
        <>
            <div>Again skipping things <input type="text" onChange={() => dispatch({ type: "SOMETHING" })}/></div>
            <div>
                {
                    state.map((item, index) => {
                        <>
                            <input type="text"/>
                            <button onClick={() => dispatch({type: "REMOVE_GOAL", payload: {index: index}})}>Remove</button>
                        </>
                    })
                }
            </div>
        </>
    );
}

return default AnotherFile;

Observations: On clicking the Remove button present in anotherfile.js file, dispatch function is getting triggered and previous state present inside reducer is getting updated and properly consoling as well. But same is not getting reflected on the UI. Consoling state in the components is not showing anything even after using useEffect with the state as a dependency.

Note: all imports/exports are done correctly. This is just an abridged version of my code just to highlight the problem I’m facing.

Source: Ask Javascript Questions

LEAVE A COMMENT