{"id":20976454,"url":"https://github.com/architgargpro/hooks-blog","last_synced_at":"2025-06-16T01:39:37.332Z","repository":{"id":147903482,"uuid":"224601895","full_name":"ArchitGargPro/Hooks-blog","owner":"ArchitGargPro","description":"Hooks, Getting in a New Relationship: A kickstart for beginners for starting with React Hooks","archived":false,"fork":false,"pushed_at":"2019-11-28T08:21:55.000Z","size":4,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-13T09:21:04.549Z","etag":null,"topics":["beginner-friendly","customhooks","hooks","react","reacthook","reacthooks","reactjs","usecontext","useeffect","usestate"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ArchitGargPro.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-11-28T08:10:28.000Z","updated_at":"2019-11-28T08:23:43.000Z","dependencies_parsed_at":"2023-05-27T21:30:30.603Z","dependency_job_id":null,"html_url":"https://github.com/ArchitGargPro/Hooks-blog","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ArchitGargPro/Hooks-blog","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ArchitGargPro%2FHooks-blog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ArchitGargPro%2FHooks-blog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ArchitGargPro%2FHooks-blog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ArchitGargPro%2FHooks-blog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ArchitGargPro","download_url":"https://codeload.github.com/ArchitGargPro/Hooks-blog/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ArchitGargPro%2FHooks-blog/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260082766,"owners_count":22956341,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["beginner-friendly","customhooks","hooks","react","reacthook","reacthooks","reactjs","usecontext","useeffect","usestate"],"created_at":"2024-11-19T04:54:00.809Z","updated_at":"2025-06-16T01:39:37.301Z","avatar_url":"https://github.com/ArchitGargPro.png","language":null,"readme":"# Hooks, Getting in a New Relationship\n##### Introducing React Hooks\n\n### INTRO\nOnce upon a time!!! \nIn 2018, at the React Conference \"Hooks\" was officially Introduced to React.\n\nThat's all for GK.\n\nHooks arrived as a savior for developers who were struggling in maintaining hundreds of states for hundreds of components.\n\nThey let you use state and other React features without writing a class. Now, you can kick out classes from your components.\n\u003eNo need to worry, There are no plans to remove classes from React permanently, _yet_\n\nYou can adopt Hooks gradually,\nHooks work side-by-side with existing code so there is no rush to migrate to Hooks. \n\u003eYou don’t have to learn or use Hooks right now if you don’t want to.\n### WHY GO FOR HOOKS?\nYou might be thinking why you need to learn one more feature? The answer is here: \n* It helps when you need to maintain too many components and states. \n* Completely opt-in. \nYou can try Hooks in a few components without rewriting any existing code.\n* A “_wrapper hell_” of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could filter them out in DevTools, this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic, here Hooks made an appearance.\n* With Hooks code Reusability is improved, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy[](https://reactjs.org/docs/hooks-intro.html#motivation). This makes it easy to share Hooks among many components or with the community.\n* render props and higher-order components try to solve some problems but make code harder to follow, because it requires to restructure your components.\n* components might perform some data fetching in componentDidMount and componentDidUpdate. However, the same componentDidMount method might also contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.\n* It’s not always possible to break these components into smaller ones because the stateful logic is all over the place. It’s also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library.\n* class components can encourage unintentional patterns that make these optimizations fall back to a slower path\n\n### How Hooks Affect the Coding Style\n\n1. Say bye! to class\n##### Without Hooks:\n_Class Components_\n```\nclass Clock extends React.Component {\n    ...\n    ...\n    render() {\n\t    return (\n\t\t\t\u003cdiv\u003e\n\t\t\t\t\u003ch1\u003e...something...\u003c/h1\u003e\n\t\t\t\u003c/div\u003e\n\t\t);\n\t}\n}\n```\n##### With Hooks:\n_Function Components_\n```\nfunction Example() {\n    ... // Hooks can be used here\n    ...\n    render() {\n\t    return (\n\t\t\t\u003cdiv\u003e\n\t\t\t\t\u003ch1\u003e...something...\u003c/h1\u003e\n\t\t\t\u003c/div\u003e\n\t\t);\n\t}\n}\n```\n###### OR like this:\n```\nfunction Example = () =\u003e {\n    ... // Hooks can be used here\n    ...\n    render() {\n\t    return (\n\t\t\t\u003cdiv\u003e\n\t\t\t\t\u003ch1\u003e...something...\u003c/h1\u003e\n\t\t\t\u003c/div\u003e\n\t\t);\n\t}\n}\n```\n*\u003e you can also pass props to the function:* \n```\nfunction Example(props) {\n    ... // Hooks can be used here\n    ...\n}\n```\n###### OR like this:\n```\nfunction Example = (props) =\u003e {\n    ... // Hooks can be used here\n    ...\n}\n```\n\u003eprops can be accessed like this -\u003e `const v = props.value`\n\n2. Creating a local state\n##### Without Hooks:\n```\nconst state = {\n    x: 10,\n    y: 'hello',\n    z: {\n        word: \"world!\"\n    }\n}\n```\n##### With Hooks:\n\u003euseState is used to set the initial value for a local state.\n```\n// this is How we declare a new state variable\nconst [color, setColor] = useState('Yellow');\n\n// declaring multiple state variables\nconst [x, setX] = useState(10);\nconst [y, setY] = useState('hello');\nconst [z, setZ] = useState([{\n    word: \"world!\",     \n}]);\n```\n\n3. Accessing state: a Breakup With `this`\n\n##### Without Hooks:\n```\nconstructor(props) {\n    this.state = { text: 'demo' };\n}\n\nrender() {\n    return (\n        \u003cdiv\u003e\n            \u003ch1\u003eThis is { this.state.text }\u003c/h1\u003e\n        \u003c/div\u003e\n    );\n}\n```\n\n##### With Hooks:\n\u003eWhile using hooks, state variables can be accessed directly\n```\nconst [text, setText] = useState('demo');\n\nrender() {\n    return (\n        \u003cdiv\u003e\n            \u003ch1\u003eThis is { text }\u003c/h1\u003e\n        \u003c/div\u003e\n    );\n}\n```\n\n4. Changing the State\n\n##### Without Hooks:\n```\n...\nthis.state = {\n    a: 1,\n    b: 2,\n    fruit: 'apple'\n}\n\n...\n{\n    this.setState({\n        ...state,\n        fruit: 'orange'\n    });\n}\n```\n\n##### With Hooks:\n```\nconst [fruit, setFruit] = useState('apple');\n\n...\n{\n    setFruit('orange')\n}\n```\n\n5. Effect of the Effect Hook\n\n\u003e- React runs the effects after every render, including the first render.\n\u003e- With useEffect() we can run a script after each update or after a particular change.\n\u003e- Lifecycle methods _componentDidMount, componentDidUpdate or componentWillUnmount_ can be replaced with useEffect()\n\n```\n// To run with each Update\nuseEffect(() =\u003e {\n    // Do something\n});\n\n\n// run only when value of \"color\" is changed\nuseEffect(() =\u003e {\n    // Do something\n}, [color]);\n\n\n// run only on first render\nuseEffect(() =\u003e {\n    // Do something\n}, []);\n```\nLet's see some usages, in lifecycle methods  \n--- ComponentDidMount\n##### Without Hooks:\n```\ncomponentDidMount() {\n    // do something\n    const cat = \"tom\";\n    this.setState({\n        ...state,\n        animal: cat\n\t});\n}\n```\n\n##### With Hooks:\n```\nuseEffect(() =\u003e {\n    // Do Something\n    const cat = \"tom\";\n    setAnimal(cat);\n}, []);\n```\n--- ComponentDidUpdate\n##### Without Hooks:\n```\ncomponentDidUpdate() {\n    // do something\n    const cat = \"tom\";\n    this.setState({\n        ...state,\n        animal: cat\n\t});\n}\n```\n##### With Hooks:\n```\nuseEffect(() =\u003e {\n    // Do Something\n    const cat = \"tom\";\n    setAnimal(cat);\n})\n```\nabove snippet will run the code at every update including the first render acting as a combination of _componentDidMount and componentDidUpdate_, if you want to prevent it from running on first render, then it can be done by keeping a check of first render, like this: \n```\nconst [isFirstRender, setIsFirstRender] = useState(true);\n\nuseEffect(() =\u003e {\n    if (isFirstRender) {\n        setIsFirstRender(false);\n    } else {\n        // do Something\n        const cat = \"tom\";\n\t\tsetAnimal(cat);\n    }\n}\n```\n\n--- ComponentWillUnmount\n\n#### Without Hooks:\n```\ncomponentWillUnmount() {\n    // Do Something\n}\n```\n##### With Hooks:\n\u003eJust return a function ( named or anonymous ) for cleanup, that we do in ComponentWillUnmount\n```\nuseEffect(() =\u003e { \n    return () =\u003e {\n        // Do something\n    }\n});\n```\n\n6. Getting the context with the Context Hook\n\n`useContext()` takes a context object as the parameter and returns the corresponding context values at that time. Refer to the example below for a better understanding.\n```\n// for example, We have\nconst flowers = {\n\tsunflower: {\n\t\tpetals: 25,\n\t\tcolor: \"yellow\"\n\t},\n\tdaisy: {\n\t\tpetals: 5,\n\t\tcolor: \"white\"\n\t},\n\trose: {\n\t\tpetals: 30,\n\t\tcolor: red\n\t}\n};\n\n\n// Creating our context\nconst MyContext = React.createContext( flowers.rose );\n\n\n// Wrappin the component with \u003cMyContext.Provider\u003e\nfunction App() {\n\treturn (\n\t\t\u003cMyContext.Provider value={ flowers.sunflower }\u003e\n\t\t\t\u003cMyComponent /\u003e\n\t\t\u003c/MyContext.Provider\u003e\n\t)\n}\n```\nThe current context value is determined by the value of the `value` prop passed in the nearest `\u003cMyContext.Provider\u003e` in which the component is wrapped.\n```\n\n// ... somewhere in our function component ...\nconst flower = useContext(MyContext);\n\n```\nNow the flower will have the value of rose:\n`{\npetals: 30,\ncolor: \"red\"\n}`\nand can be used as \n`\u003cp\u003eColour of rose is { flower.color }.\u003c/p\u003e`   \nIt will run each time when the context is updated\n\n\u003eYou must have got the '_context_' of this blog if you are still here, kindly have a look at \"Some rules to remember\" below:\n### Some rules to remember\n- _never be conditional with Hooks_: \n    don't call hooks inside loops or conditions, call Hooks at the _Top level_\n- _don't call hooks from nested functions_:\n    call only _from React Function components_ or _custom hooks_\n\u003eMore details can be found in official React docs, available [here](https://reactjs.org/docs/hooks-rules.html)\n\n### More about Hooks\n##### More Hooks\nSome other commonly used Hooks are: \n- [Basic Hooks](https://reactjs.org/docs/hooks-reference.html#basic-hooks)\n    \n    -   [useState](https://reactjs.org/docs/hooks-reference.html#usestate)\n    -   [useEffect](https://reactjs.org/docs/hooks-reference.html#useeffect)\n    -   [useContext](https://reactjs.org/docs/hooks-reference.html#usecontext)\n-   [Additional Hooks](https://reactjs.org/docs/hooks-reference.html#additional-hooks)\n\n    -   [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer)\n    -   [useCallback](https://reactjs.org/docs/hooks-reference.html#usecallback)\n    -   [useMemo](https://reactjs.org/docs/hooks-reference.html#usememo)\n    -   [useRef](https://reactjs.org/docs/hooks-reference.html#useref)\n    -   [useImperativeHandle](https://reactjs.org/docs/hooks-reference.html#useimperativehandle)\n    -   [useLayoutEffect](https://reactjs.org/docs/hooks-reference.html#uselayouteffect)\n    -   [useDebugValue](https://reactjs.org/docs/hooks-reference.html#usedebugvalue)   \nYou can see a list of React Hooks [here](https://reactjs.org/docs/hooks-reference.html).\n##### Custom Hooks\nA custom Hook is a function whose name starts with ”`use`” and that may call other Hooks and, lets you extract component logic into reusable functions.\n\nLet's create a custom Hook `useColor` that returns the color of the flower whose ID is passed as argument:\n```\nfunction useColor(flowerID) {\n    const [color, setColor] = useColor(null);\n\n    useEffect(() =\u003e {\n        /*    Extract the value of colour of the flower from the database and set the value of color using setColor()    */\n    });\n\n    return color;\n}\n```\nNow, we can use our custom hook,\n```\n{\n    // To get the colour of the flower with ID = 10\n    const color = useColor(10);\n}\n```\nLearn more about how to create the [custom hooks](https://reactjs.org/docs/hooks-custom.html) in detail.\n\n[see](https://reactjs.org/docs/hooks-intro.html) official docs for React Hooks.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farchitgargpro%2Fhooks-blog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farchitgargpro%2Fhooks-blog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farchitgargpro%2Fhooks-blog/lists"}