Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize the react functional component state from props

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?

like image 567
Kiran Maniya Avatar asked Dec 11 '19 15:12

Kiran Maniya


People also ask

Can we use state props in functional component?

As mentioned earlier, it was not possible to use state in functional components because the setState() method was only supported in the class components. But with React hooks, now it is possible to use state in functional components.

How do you update state in functional component React?

Give it a value. Create another method inside the class and update the state of the component using 'this. setState()' method. Pass the state object in a JSX element and call the method to update the state on a specific event like button click.


Video Answer


2 Answers

Yes, this can be possible with functional component too! You just need to add useEffect to listen to prop change for initializing state with prop value

export const newComponent = (props) => {
  const { path, value, info, update } = props;
  const [val, setVal] = useState(value);

  useEffect(() => {
    setVal(value);
  }, [value]);

  return <div>{val}</div>;
};

Attching sandbox link

https://codesandbox.io/s/confident-agnesi-ohkq7?file=/src/MakeComponent.js

like image 114
Riddhi Patel Avatar answered Oct 27 '22 14:10

Riddhi Patel


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])
like image 22
demkovych Avatar answered Oct 27 '22 13:10

demkovych