1

i started learning redux and i've got the following question. so I have a redux store with initial state and i also have a component which is responsible (dispatching an action) with user inputted data. so if the inputs are controlled should i set their value property in redux store (initalState) and dispatch an action every time value changes or should i use local state of component -

 class Calc ...
   constructor(props){
       super(props);
       this.handleChange = this.handleChange.bind(this);
       this.state = {
           inputVal: ''
       }
   }

   handleChange(e){
      this.setState({
         [e.target.name]: e.target.value
      })
   }

   render(){
     return(
          <div>
              <input type="text" name="inputVal" value={this.state.inputVal} onChange={this.handleChange} />
          </div>
     )
   }

2 Answers 2

2

in my opinion, before you store something in redux store, you should ask yourself some questions:

  • if my state "inputVal" will be shared between the other components?
  • if the change of my "inputVal" have some impacts on the other components

If you get the absolute answer "YES", you might need to store this state "inputVal" in redux state.

If NO, you do NOT need to store this state in redux. Instead of it, just handle the state within your component "Cal"

Sign up to request clarification or add additional context in comments.

Comments

2

When a component is connected to Redux store it gets notified about the changes done to the store.

Therefore if
- two or more components would benefit from being notified about the state changes and
- these components are not in parent-child type of relationship when it's very easy for typically the parent to be aware about the changes related to self and the child and then let the child know what it should do by changing its props

then use Redux store.

Additionally there might be entirely different situation when just one single (or maybe several) component(s) need to be notified about navigation changes e.g user using Back/Foward browser buttons. In such case use Redux as well, in conjuction with Router that automatically dispathes an action to Redux store with relevant payload.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.