Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 28, 2021 08:45 am GMT

Difference between react props vs. state

One of the core concepts of react is the difference between props and state. Only changes in props and state trigger react to re-render components and update the DOM.

The biggest difference is that re-rendering of the component based on input in state is done entirely within the component, whereas you with using props can receive new data from outside the component and re-render.

Props

props allows you to pass data from a parent component to a child component.

//Parent Componentconst books = () => {    return (<div> <Book title = "Data structures and algorithms with JAVA" /> </div>   );}//Child componentconst book = (props) => {    return (         <div>            <h1>{props.title}</h1>        </div>    )}
Enter fullscreen mode Exit fullscreen mode

Explanation: Now. props is passed in to the child component and the functional component the passes the props as an argument which in turn will be handled as an object. The property title is accessible in the child component from the parent component.

State

Only class-based react components can define and use state. Its although possible to pass state to a functional component but functional components cant edit them directly.

class NewBook extends Component {    state = {        number: ''    };    render() {        return (             <div>{this.state.number}</div>        );    }}
Enter fullscreen mode Exit fullscreen mode

As you can see the NewBook component contains a defined state. This state is accessible through this.state.number and can be returned in the render() method.


Original Link: https://dev.to/code_runner/react-props-vs-state-56l5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To