G
G
GF2020-04-26 14:05:30
React
GF, 2020-04-26 14:05:30

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")
);


store.ts:

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
  reducer,
  composeWithDevTools(applyMiddleware(sagaMiddleware))
);

sagaMiddleware.run(rootSaga);


app.tsx:

export const App: FC = () => {
  console.log("start App");
  const state = useSelector((state: AppState) => state.isLoading);
  console.log(state);
  return <h1>hey</h1>;
};


sagas.ts:

export function* watchFetchFilm() {
  console.log("start watchFetchFilm");

  yield takeLatest(FETCH_FILM_REQUESTED, fetchFilm);
}

export function* rootSaga() {
  console.log("start root");
  yield watchFetchFilm();
}


console output:
5ea56a84b102f538201805.png

Why does App render twice?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dev null, 2020-04-26
@curious-101

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.

You can use reselect to memoize redux store slices. Well, read the difference between redax hooks and connect()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question