DEV Community

loading...

Discussion on: Flawless React State Management: useReducer and Context API

Collapse
droidmakk profile image
Afroze Kabeer Khan. M

I've been preaching this approach, but the only caveat I feel in this is context api does unnecessary re-renders.
Which needs to be again carefully memoized as to prevent unnecessary re-renders.

What's your thought on this?

Collapse
sanderdebr profile image
sanderdebr Author • Edited

True, but I've noticed that React is very smart in comparing and updating, it only updates the components that actually are affected by a state difference, even before memoizing them. I'm using this technique in a production app and only the affected components seem to be re-rendering.

However, I would advise to only store your app-wide state with the context api, otherwise use local state - for example for input forms. So the app would be a combination of context stores and local stores then. Otherwise switch to a state management lib like Redux.

How are you managing state currently?

Collapse
droidmakk profile image
Afroze Kabeer Khan. M

I'd say you can use html and native JavaScript implementations for input fields since state updates are async the user feedback can be sometimes bad. But in special cases you can use it, I suppose...

Collapse
polaroidkidd profile image
Daniel Einars

Even for friends the context API becomes a performance issue when your form is split over multiple components.

Collapse
markerikson profile image
Mark Erikson

it only updates the components that actually are affected by a state difference

Depends on what you mean by "update" here.

Yes, React only modifies the DOM if your component's render output changes.

However, React always re-renders components recursively by default, even if the props and state haven't changed. It's a very common misconception that React automatically skips rendering if the props are the same - that's an optimization you have to apply.

See my post A (Mostly) Complete Guide to React Rendering Behavior for details.

Collapse
markerikson profile image
Mark Erikson

Yep. I actually just wrote a post a few days ago that covers this:

Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux)

My primary point is clarifying the actual capabilities and purposes for Context, useReducer, and Redux, but as part of that I also discuss some of the behavior differences.

I'd also suggest reading my posts A (Mostly) Complete Guide to React Rendering Behavior and React, Redux, and Context Behavior, which cover more details on the rendering behavior aspects.

Collapse
droidmakk profile image
Afroze Kabeer Khan. M

Cool...

Collapse
matjones profile image
Mat Jones

Came here to say this. This is the reason that I think Context API is not really suitable for app-wide state management unless that state is going to change very infrequently.