Answer the question
In order to leave comments, you need to log in
UseSelector: Why is the component rendered twice?
I started writing a React + Redux project with sagas and noticed that when using the UseSelector hook, the component is re-rendered.
Simplified project structure:
index.ts:
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(sagaMiddleware))
);
sagaMiddleware.run(rootSaga);
export const App: FC = () => {
console.log("start App");
const state = useSelector((state: AppState) => state.isLoading);
console.log(state);
return <h1>hey</h1>;
};
export function* watchFetchFilm() {
console.log("start watchFetchFilm");
yield takeLatest(FETCH_FILM_REQUESTED, fetchFilm);
}
export function* rootSaga() {
console.log("start root");
yield watchFetchFilm();
}
Answer the question
In order to leave comments, you need to log in
The react devtools has a Profiler tab, there is an option - show what caused the component to render. At a glance, the state of the redux storage has changed after the action, isLoading may not have changed its value, but useSelector compares by reference.
When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question