D Kuzmanovic
D Kuzmanovic

Reputation: 45

Passing props to useState React

I' am trying to use props coming from redux as a starting point for rendering my state-full component like this:

const MyComp = (props) => {

    const initState = {
        newAttribs: [...props.attribs]
        };

    const [state, setState] = useState(initState)
    console.log(state)

};

const mapStateToProps = (fromRedux) => {...};
const mapDispatchToProps = (dispatch) => {...};

export default connect(mapStateToProps, mapDispatchToProps)(React.memo(MyComp));

But if I console.log(state) it shows empty array for newAttribs even though in initState newAttribs are there.

Can someone shed some light on how to do this properly? Thanks.

EDIT:

I've made an error while posting code snippet, I updated it now. const mapStateToProps and const mapDispatchToProps obviously have to be outside of the component scope and they are.

Upvotes: 3

Views: 11360

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282030

There are three things that you need to take care of

  1. The argument to useState is only used once during initial load and state won't update when props change
  2. mapStateToProps and mapDispatchToProps should be defined outside of the component scope
  3. When props.attribs changes you need to update your component state which you can do using useEffect

Example

const MyComp = (props) => {

    const initState = {
        newAttribs: [...props.attribs]
    };

    const [state, setState] = useState(initState)

    useEffect (() => { 
          setState({ ...state, newAttribs: [...props.attribs] }) 
    }, [props.attribs])
    console.log(state)


};

const mapStateToProps = (fromRedux) => {...};
const mapDispatchToProps = (dispatch) => {...};
export default connect(mapStateToProps, mapDispatchToProps)(React.memo(MyComp));

If the data from redux store is available before initial mount you will see it in console.log

Upvotes: 6

Related Questions