Search code examples
javascriptreactjswebdispatchreact-context

Why would we use SetState while we can change Component's values from parent component?


I am trying to understand dispatch, reducer, and action in react (ContextApi). But my question is: While we can change anything in the child component from the parent component, why do we need to use "setState" inside of child components? I mean if I want to change something in the component, if I can change it from a parent,(which I can with dispatch, reducer and action), i wouldn't use the SetState function inside of the Component. If you can help me, I would be so happy. Thanks!


Solution

  • You don't need to use setState. You can just pass the dispatch function as prop if you need to control the state within the child component.

    Using setState in a child component is useful if, you for example need to filter the input or change the state locally before rendering. But all this can be achieved without usestate.

    But if you are trying to learn reducers I don't really get the question the hook in the child component can just be another reducer in case you want to control it independently.