DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

SM Toufiqul Hoque
SM Toufiqul Hoque

Posted on

State-Props

State

States are allowed to create and manage their own data. So unlike props , state can not pass data with state, but they can create and manage it internally.

class Test extends React.Component {    
    constructor() {    
        this.state = {          
            name: "Toufiq"    
        };  
    }    
    render() {    
        return (      
            <div>             
              <p>{this.state.name}</p>      
            </div>    
        );  
    }
}
Enter fullscreen mode Exit fullscreen mode

There is nothing useful going on in this case, but imagine doing something different based on the prop value, maybe setting a state value would be better.

A child component should never change its properties, so if something changes a variable, it should belong to the component state.

Child components can also use props to gain access to methods in the parent component. This is a good way to centralize management of state in the parent component and avoid children from having to manage their own state.

State should not be modified directly, but it can be modified with a special method called setState( ).

this.state.id = β€œhello”; // wrong

this.setState({         // correct  
    id: "hello"
});

Enter fullscreen mode Exit fullscreen mode

Props
Props used to pass data between React components. React data flow between component is unidirectional(from parent components to child components)

Example

class pComponent extends Component {    
    render() {    
        return (        
            <cComponent name="First Child" />    
        );  
    }
}

const cComponent = (props) => {    
    return <p>{props.name}</p>; 
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Let's Get Wacky


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category

β†’ Join the Hackathon <-