State and Props
State and Props
Hooks :
✓ Hook is nothing but a function and present only in function based
component.
✓ Hooks are introduced React 16.8 version onwards.
✓ Why Hooks are used in ReactJS?
➢ Hooks allows functional component to have access to state and
other React features which present in Class based components.
Basic hooks :
1) useState ( )
2) useEffect ( )
3) useContext ()
useState( ) :
• This hook allows you to add state to FBC.
• It return an array let [ ] = useState( )
• It accepts 2 values
a. current state b. Updator function.
• Initialization of useState( )
main.jsx
main.jsx
PROPS :
✓ Props are shorthand for properties.
✓ Props is an object.
✓ Props is a way to communicate between the component.
✓ Props are used to send the data present in one component into another
component.
✓ Props are sent html like attribute format.
Example : Sending data present in App.jsx into Child.jsx. Here App.jsx acts as
a parent and Child.jsx acts as child.
Ex:1
App.jsx :
Child.jsx
Props Children :
App.jsx :
Child.jsx
Child.jsx
Destructuring while receiving props children
App.jsx
Child.jsx
Child.jsx
Default Props :
✓ Suppose if we are not actually sending the data but we want something to print in
Child Component then we should go for default props.
✓ Default props works only when we don’t send data.
✓ If we send the data along with default props, the sending data will override the default
props.
Ex:1
App.jsx
Child.jsx
Child.jsx
PropTypes:
✓ They are used to specify the expected data types of properties (props) that a
component should receive.
Steps:
➢ Install PropTypes using command npm i prop-types
➢ After installing import it in the component where you are receiving the props.
App.jsx
Child.jsx
Here in App.jsx we are sending age = “30” as a string but expected datatype of age is integer
so we will get warning in console along with output