How to initialize the react functional component state from props

Kiran Maniya picture Kiran Maniya · Dec 11, 2019 · Viewed 9.4k times · Source

I'm using React hooks for app state, I wondered about how to initialize the functional component state using props? The useState hook doc says something definitive like,

const [count, setCount] = useState(0);

I want to initialize that 0 value by the value of props being passed to the component. The Older as,

import React from 'react';

export default class Sym extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            sym : [0,3,2,8,5,4,1,6],
            active: this.props.activeSym
        }
        this.setActive = this.setActive.bind(this);
    }

    setActive(itemIndex){
        this.setState({
            active: itemIndex
        });
    }

    render(){
        return (
             <div><h1>{ this.state.sym[this.state.active]}</h1></div>
        );
    }
}

works fine. Where the parent Component passes activeSym prop and Sym component initializes the state with it using this.props.activeSym in constructor. Is there any workaround to achieve same in function component?

Answer

demkovych picture demkovych · Dec 11, 2019

First you can define it from props (if the prop exist):

const [count, setCount] = useState(activeSym);

And then you can update this value, when prop doesn't have a value immediately (when component rendered):

useEffect(() => {
  if (activeSym) {
    setCount(activeSym);
  }
}, [activeSym])