Closed
Description
import React, { useReducer } from 'react';
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case 'increment':
return state;
case 'decrement':
return state;
case 'reset':
return initialState;
default:
return state;
}
};
export const UseReducer = () => {
const [count, dispatch] = useReducer(reducer, initialState);
console.log('UseReducer Render');
return (
<div>
<div>Count = {count}</div>
<button onClick={() => dispatch('increment')}>Increment</button>
<button onClick={() => dispatch('decrement')}>Decrement</button>
<button onClick={() => dispatch('reset')}>Reset</button>
</div>
);
};
- In react 17, after the component has finished its initial render, the state value is zero, and then when i now click on the reset button which again sets the state value to zero react will not re-render the component
- Thus,
console.log('UseReducer Render');
is printed only once. - But after updating version to 18, whenever i click reset button,
console.log('UseReducer Render');
is printed - I used same code but, result is different
- So i want to know why component is rendered when same state is passed to useReducer in React 18.
- Comparing useState, using useState hook, when same state is passed, component is not re-renderd in react 17 and react 18.