I want to declare default props in a functional component
normally we would do this
function Body() {
    static defaultProps = {
        counter: 0
    }
    return (
        <div>
            body
        </div>
    );
}
this obviously doesn't work
You can define default props this way: export class Counter extends React. Component { constructor(props) { super(props); this. state = {count: props.
While most React components receive their props from a parent component, it's also possible to specify default props. To do so, you simply assign a defaultProps object to the component; when React renders the component, the default props will be used unless the parent overrides them.
To set a default value for an input element in React: Pass the default value as a parameter to the useState hook for controlled fields. Set the defaultValue prop on uncontrolled input fields.
Because defaultProps on functions will eventually get deprecated.
This is usually called a functional component, not a hook component.
For the defaultProps you can do it like this:
const Body = ({ counter }) => {
    return (
        <div>
            {counter}
        </div>
    );
}
Body.defaultProps = {
    counter: 0
}
                        function Body({counter=0}) {
    return (
        <div>
            body
        </div>
    );
}
counter now has initial value of 0
Hooks are just regular functions, you can define default values the same way as you define them in regular functions
function useNameHook(initialName = "Asaf") {
  const [name, setName] = useState(initialName);
  // you can return here whatever you want, just the name,
  // just the setter or both
  return name;
}
function Comp({ name }) {
  const myName = useNameHook(name);
  return <h1>Hello {myName}</h1>;
}
function App() {
  return (
    <div className="App">
      {/* without name prop */}
      <Comp />
      {/* with name prop */}
      <Comp name="angry kiwi" />
    </div>
  );
}
                        You can do that simply like this
const Body = (props) => {
    const {foo = 'defaultValue'} = props;
    return <div>{foo}</div> // It will show defaultValue if props foo is undefined
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With